From 7f91fa7ed81ec3b15a57f135cba4e37c19baf6e7 Mon Sep 17 00:00:00 2001 From: Nabarun Gogoi Date: Fri, 14 Apr 2023 17:22:44 +0530 Subject: [PATCH] Remove watchers after moving them out to their own repos (#365) * Remove all watchers after moving them out * Add missing dependencies --- packages/address-watcher/.eslintignore | 5 - packages/address-watcher/.eslintrc.json | 28 - packages/address-watcher/.gitignore | 6 - packages/address-watcher/README.md | 33 - .../address-watcher/environments/local.toml | 28 - packages/address-watcher/package.json | 64 - .../address-watcher/src/cli/watch-address.ts | 51 - packages/address-watcher/src/database.ts | 141 -- .../address-watcher/src/entity/Account.ts | 19 - .../src/entity/BlockProgress.ts | 24 - packages/address-watcher/src/entity/Trace.ts | 27 - packages/address-watcher/src/fill.ts | 108 - packages/address-watcher/src/indexer.ts | 111 - packages/address-watcher/src/job-runner.ts | 78 - packages/address-watcher/src/resolvers.ts | 73 - packages/address-watcher/src/schema.ts | 79 - packages/address-watcher/src/server.ts | 92 - packages/address-watcher/src/tx-watcher.ts | 126 -- .../src/types/common/main.d.ts | 7 - .../src/types/common/package.json | 6 - packages/address-watcher/src/util.test.ts | 150 -- packages/address-watcher/src/util.ts | 33 - packages/address-watcher/tsconfig.json | 77 - packages/cli/package.json | 2 + packages/codegen/package.json | 2 + packages/eden-watcher/.eslintignore | 2 - packages/eden-watcher/.eslintrc.json | 28 - packages/eden-watcher/README.md | 16 - packages/eden-watcher/codegen.yaml | 43 - packages/eden-watcher/environments/local.toml | 75 - packages/eden-watcher/package.json | 72 - .../src/artifacts/DistributorGovernance.json | 723 ------ .../src/artifacts/EdenNetwork.json | 942 -------- .../src/artifacts/MerkleDistributor.json | 1482 ------------- .../src/cli/checkpoint-cmds/create.ts | 44 - .../src/cli/checkpoint-cmds/verify.ts | 40 - packages/eden-watcher/src/cli/checkpoint.ts | 39 - packages/eden-watcher/src/cli/export-state.ts | 38 - packages/eden-watcher/src/cli/import-state.ts | 39 - packages/eden-watcher/src/cli/index-block.ts | 38 - packages/eden-watcher/src/cli/inspect-cid.ts | 38 - .../src/cli/reset-cmds/job-queue.ts | 22 - .../eden-watcher/src/cli/reset-cmds/state.ts | 24 - .../src/cli/reset-cmds/watcher.ts | 37 - packages/eden-watcher/src/cli/reset.ts | 24 - .../eden-watcher/src/cli/watch-contract.ts | 38 - packages/eden-watcher/src/client.ts | 55 - packages/eden-watcher/src/database.ts | 272 --- packages/eden-watcher/src/entity/Account.ts | 29 - packages/eden-watcher/src/entity/Block.ts | 67 - .../eden-watcher/src/entity/BlockProgress.ts | 48 - packages/eden-watcher/src/entity/Claim.ts | 38 - packages/eden-watcher/src/entity/Contract.ts | 24 - .../eden-watcher/src/entity/Distribution.ts | 38 - .../eden-watcher/src/entity/Distributor.ts | 24 - packages/eden-watcher/src/entity/Epoch.ts | 45 - packages/eden-watcher/src/entity/Event.ts | 38 - .../eden-watcher/src/entity/FrothyEntity.ts | 21 - packages/eden-watcher/src/entity/Network.ts | 45 - packages/eden-watcher/src/entity/Producer.ts | 37 - .../eden-watcher/src/entity/ProducerEpoch.ts | 39 - .../entity/ProducerRewardCollectorChange.ts | 31 - .../eden-watcher/src/entity/ProducerSet.ts | 24 - .../src/entity/ProducerSetChange.ts | 39 - .../eden-watcher/src/entity/RewardSchedule.ts | 33 - .../src/entity/RewardScheduleEntry.ts | 31 - packages/eden-watcher/src/entity/Slash.ts | 32 - packages/eden-watcher/src/entity/Slot.ts | 45 - packages/eden-watcher/src/entity/SlotClaim.ts | 45 - packages/eden-watcher/src/entity/Staker.ts | 28 - packages/eden-watcher/src/entity/State.ts | 36 - .../src/entity/StateSyncStatus.ts | 17 - .../eden-watcher/src/entity/Subscriber.ts | 21 - .../eden-watcher/src/entity/SyncStatus.ts | 36 - packages/eden-watcher/src/fill.ts | 44 - packages/eden-watcher/src/gql/index.ts | 3 - .../eden-watcher/src/gql/mutations/index.ts | 4 - .../src/gql/mutations/watchContract.gql | 3 - .../eden-watcher/src/gql/queries/account.gql | 19 - .../eden-watcher/src/gql/queries/block.gql | 20 - .../eden-watcher/src/gql/queries/claim.gql | 14 - .../src/gql/queries/distribution.gql | 12 - .../src/gql/queries/distributor.gql | 12 - .../eden-watcher/src/gql/queries/epoch.gql | 53 - .../eden-watcher/src/gql/queries/events.gql | 139 -- .../src/gql/queries/eventsInRange.gql | 139 -- .../eden-watcher/src/gql/queries/getState.gql | 15 - .../src/gql/queries/getStateByCID.gql | 15 - .../eden-watcher/src/gql/queries/index.ts | 24 - .../eden-watcher/src/gql/queries/network.gql | 43 - .../eden-watcher/src/gql/queries/producer.gql | 10 - .../src/gql/queries/producerEpoch.gql | 17 - .../queries/producerRewardCollectorChange.gql | 8 - .../src/gql/queries/producerSet.gql | 13 - .../src/gql/queries/producerSetChange.gql | 8 - .../src/gql/queries/rewardSchedule.gql | 33 - .../src/gql/queries/rewardScheduleEntry.gql | 8 - .../eden-watcher/src/gql/queries/slash.gql | 12 - .../eden-watcher/src/gql/queries/slot.gql | 21 - .../src/gql/queries/slotClaim.gql | 21 - .../eden-watcher/src/gql/queries/staker.gql | 7 - .../src/gql/subscriptions/index.ts | 4 - .../src/gql/subscriptions/onEvent.gql | 142 -- packages/eden-watcher/src/hooks.ts | 71 - packages/eden-watcher/src/indexer.ts | 941 -------- packages/eden-watcher/src/job-runner.ts | 47 - packages/eden-watcher/src/resolvers.ts | 532 ----- packages/eden-watcher/src/schema.gql | 464 ---- packages/eden-watcher/src/server.ts | 42 - .../eden-watcher/test/queries/account.gql | 13 - packages/eden-watcher/test/queries/block.gql | 20 - packages/eden-watcher/test/queries/claim.gql | 12 - .../test/queries/distribution.gql | 12 - .../eden-watcher/test/queries/distributor.gql | 8 - packages/eden-watcher/test/queries/epoch.gql | 19 - .../eden-watcher/test/queries/network.gql | 20 - .../eden-watcher/test/queries/producer.gql | 10 - .../test/queries/producerEpoch.gql | 12 - .../queries/producerRewardCollectorChange.gql | 8 - .../eden-watcher/test/queries/producerSet.gql | 8 - .../test/queries/producerSetChange.gql | 8 - .../test/queries/rewardSchedule.gql | 17 - .../test/queries/rewardScheduleEntry.gql | 8 - packages/eden-watcher/test/queries/slash.gql | 10 - packages/eden-watcher/test/queries/slot.gql | 15 - .../eden-watcher/test/queries/slotClaim.gql | 14 - packages/eden-watcher/test/queries/staker.gql | 7 - packages/eden-watcher/tsconfig.json | 74 - packages/erc20-watcher/.eslintignore | 5 - packages/erc20-watcher/.eslintrc.json | 28 - packages/erc20-watcher/.gitignore | 10 - packages/erc20-watcher/README.md | 198 -- .../erc20-watcher/environments/local.toml | 40 - packages/erc20-watcher/hardhat.config.ts | 30 - packages/erc20-watcher/package.json | 78 - .../erc20-watcher/src/artifacts/ERC20.json | 365 ---- .../src/artifacts/ERC20NameBytes.json | 17 - .../src/artifacts/ERC20SymbolBytes.json | 17 - .../src/cli/reset-cmds/job-queue.ts | 22 - .../erc20-watcher/src/cli/reset-cmds/state.ts | 24 - .../src/cli/reset-cmds/watcher.ts | 26 - packages/erc20-watcher/src/cli/reset.ts | 24 - .../erc20-watcher/src/cli/watch-contract.ts | 27 - packages/erc20-watcher/src/client.ts | 55 - packages/erc20-watcher/src/database.ts | 282 --- .../erc20-watcher/src/entity/Allowance.ts | 34 - packages/erc20-watcher/src/entity/Balance.ts | 31 - .../erc20-watcher/src/entity/BlockProgress.ts | 49 - packages/erc20-watcher/src/entity/Contract.ts | 24 - packages/erc20-watcher/src/entity/Event.ts | 41 - packages/erc20-watcher/src/entity/State.ts | 36 - .../src/entity/StateSyncStatus.ts | 17 - .../erc20-watcher/src/entity/SyncStatus.ts | 43 - packages/erc20-watcher/src/fill.ts | 26 - packages/erc20-watcher/src/index.ts | 5 - packages/erc20-watcher/src/indexer.ts | 546 ----- packages/erc20-watcher/src/job-runner.ts | 34 - packages/erc20-watcher/src/queries.ts | 94 - packages/erc20-watcher/src/resolvers.ts | 108 - packages/erc20-watcher/src/schema.ts | 168 -- packages/erc20-watcher/src/server.ts | 29 - .../erc20-watcher/src/types/common/main.d.ts | 6 - .../src/types/common/package.json | 6 - packages/erc20-watcher/src/utils/index.ts | 118 - .../src/utils/static-token-definition.ts | 99 - .../erc20-watcher/test/contracts/GLDToken.sol | 10 - packages/erc20-watcher/test/tasks/account.ts | 12 - .../erc20-watcher/test/tasks/block-latest.ts | 18 - .../erc20-watcher/test/tasks/token-approve.ts | 34 - .../erc20-watcher/test/tasks/token-deploy.ts | 21 - .../test/tasks/token-transfer-from.ts | 37 - .../test/tasks/token-transfer.ts | 33 - packages/erc20-watcher/tsconfig.json | 77 - packages/erc721-watcher/.eslintignore | 2 - packages/erc721-watcher/.eslintrc.json | 28 - packages/erc721-watcher/.gitignore | 3 - packages/erc721-watcher/README.md | 305 --- .../erc721-watcher/environments/local.toml | 55 - packages/erc721-watcher/hardhat.config.ts | 29 - packages/erc721-watcher/package.json | 85 - .../erc721-watcher/src/artifacts/ERC721.json | 452 ---- .../src/cli/checkpoint-cmds/create.ts | 33 - packages/erc721-watcher/src/cli/checkpoint.ts | 39 - .../erc721-watcher/src/cli/export-state.ts | 27 - .../erc721-watcher/src/cli/import-state.ts | 28 - .../erc721-watcher/src/cli/index-block.ts | 27 - .../erc721-watcher/src/cli/inspect-cid.ts | 27 - .../src/cli/reset-cmds/job-queue.ts | 22 - .../src/cli/reset-cmds/state.ts | 24 - .../src/cli/reset-cmds/watcher.ts | 26 - packages/erc721-watcher/src/cli/reset.ts | 24 - .../erc721-watcher/src/cli/watch-contract.ts | 27 - packages/erc721-watcher/src/client.ts | 181 -- packages/erc721-watcher/src/database.ts | 538 ----- .../erc721-watcher/src/entity/BalanceOf.ts | 31 - .../src/entity/BlockProgress.ts | 48 - .../erc721-watcher/src/entity/Contract.ts | 24 - packages/erc721-watcher/src/entity/Event.ts | 38 - .../erc721-watcher/src/entity/GetApproved.ts | 31 - .../src/entity/IsApprovedForAll.ts | 33 - packages/erc721-watcher/src/entity/Name.ts | 27 - packages/erc721-watcher/src/entity/OwnerOf.ts | 31 - packages/erc721-watcher/src/entity/State.ts | 36 - .../src/entity/StateSyncStatus.ts | 17 - .../src/entity/SupportsInterface.ts | 30 - packages/erc721-watcher/src/entity/Symbol.ts | 27 - .../erc721-watcher/src/entity/SyncStatus.ts | 36 - .../erc721-watcher/src/entity/TokenURI.ts | 31 - .../src/entity/TransferCount.ts | 23 - .../erc721-watcher/src/entity/_Balances.ts | 31 - packages/erc721-watcher/src/entity/_Name.ts | 27 - .../src/entity/_OperatorApprovals.ts | 33 - packages/erc721-watcher/src/entity/_Owners.ts | 31 - packages/erc721-watcher/src/entity/_Symbol.ts | 27 - .../src/entity/_TokenApprovals.ts | 31 - packages/erc721-watcher/src/fill.ts | 32 - packages/erc721-watcher/src/gql/index.ts | 3 - .../erc721-watcher/src/gql/mutations/index.ts | 4 - .../src/gql/mutations/watchContract.gql | 3 - .../src/gql/queries/_balances.gql | 8 - .../erc721-watcher/src/gql/queries/_name.gql | 8 - .../src/gql/queries/_operatorApprovals.gql | 8 - .../src/gql/queries/_owners.gql | 8 - .../src/gql/queries/_symbol.gql | 8 - .../src/gql/queries/_tokenApprovals.gql | 8 - .../src/gql/queries/balanceOf.gql | 8 - .../erc721-watcher/src/gql/queries/events.gql | 39 - .../src/gql/queries/eventsInRange.gql | 39 - .../src/gql/queries/getApproved.gql | 8 - .../src/gql/queries/getState.gql | 15 - .../src/gql/queries/getStateByCID.gql | 15 - .../erc721-watcher/src/gql/queries/index.ts | 21 - .../src/gql/queries/isApprovedForAll.gql | 8 - .../erc721-watcher/src/gql/queries/name.gql | 8 - .../src/gql/queries/ownerOf.gql | 8 - .../src/gql/queries/supportsInterface.gql | 8 - .../erc721-watcher/src/gql/queries/symbol.gql | 8 - .../src/gql/queries/tokenURI.gql | 8 - .../src/gql/subscriptions/index.ts | 4 - .../src/gql/subscriptions/onEvent.gql | 39 - packages/erc721-watcher/src/hooks.ts | 145 -- packages/erc721-watcher/src/indexer.ts | 953 -------- packages/erc721-watcher/src/job-runner.ts | 36 - packages/erc721-watcher/src/resolvers.ts | 183 -- packages/erc721-watcher/src/schema.gql | 129 -- packages/erc721-watcher/src/server.ts | 31 - .../erc721-watcher/test/contracts/TestNFT.sol | 13 - packages/erc721-watcher/test/tasks/account.ts | 12 - .../erc721-watcher/test/tasks/block-latest.ts | 18 - .../erc721-watcher/test/tasks/nft-deploy.ts | 15 - .../erc721-watcher/test/tasks/nft-mint.ts | 33 - .../erc721-watcher/test/tasks/nft-transfer.ts | 34 - packages/erc721-watcher/tsconfig.json | 74 - packages/graph-node/package.json | 2 + packages/graph-test-watcher/.eslintignore | 2 - packages/graph-test-watcher/.eslintrc.json | 28 - packages/graph-test-watcher/.gitignore | 6 - packages/graph-test-watcher/README.md | 141 -- .../environments/local.toml | 72 - packages/graph-test-watcher/package.json | 73 - .../src/artifacts/Example.json | 134 -- .../src/cli/checkpoint-cmds/create.ts | 44 - .../src/cli/checkpoint-cmds/verify.ts | 40 - .../graph-test-watcher/src/cli/checkpoint.ts | 39 - .../src/cli/export-state.ts | 38 - .../src/cli/import-state.ts | 39 - .../graph-test-watcher/src/cli/index-block.ts | 38 - .../graph-test-watcher/src/cli/inspect-cid.ts | 38 - .../src/cli/reset-cmds/job-queue.ts | 22 - .../src/cli/reset-cmds/state.ts | 24 - .../src/cli/reset-cmds/watcher.ts | 37 - packages/graph-test-watcher/src/cli/reset.ts | 24 - .../src/cli/watch-contract.ts | 38 - packages/graph-test-watcher/src/client.ts | 73 - packages/graph-test-watcher/src/database.ts | 297 --- .../graph-test-watcher/src/entity/Author.ts | 42 - .../src/entity/BlockProgress.ts | 48 - .../graph-test-watcher/src/entity/Blog.ts | 47 - .../graph-test-watcher/src/entity/Category.ts | 29 - .../graph-test-watcher/src/entity/Contract.ts | 24 - .../graph-test-watcher/src/entity/Event.ts | 38 - .../src/entity/FrothyEntity.ts | 21 - .../src/entity/GetMethod.ts | 27 - .../graph-test-watcher/src/entity/State.ts | 36 - .../src/entity/StateSyncStatus.ts | 17 - .../src/entity/Subscriber.ts | 21 - .../src/entity/SyncStatus.ts | 36 - .../graph-test-watcher/src/entity/_Test.ts | 28 - packages/graph-test-watcher/src/fill.ts | 43 - packages/graph-test-watcher/src/gql/index.ts | 3 - .../src/gql/mutations/index.ts | 4 - .../src/gql/mutations/watchContract.gql | 3 - .../src/gql/queries/_test.gql | 8 - .../src/gql/queries/author.gql | 16 - .../src/gql/queries/blog.gql | 17 - .../src/gql/queries/category.gql | 7 - .../src/gql/queries/events.gql | 28 - .../src/gql/queries/eventsInRange.gql | 28 - .../src/gql/queries/getMethod.gql | 8 - .../src/gql/queries/getState.gql | 15 - .../src/gql/queries/getStateByCID.gql | 15 - .../src/gql/queries/index.ts | 10 - .../src/gql/subscriptions/index.ts | 4 - .../src/gql/subscriptions/onEvent.gql | 28 - packages/graph-test-watcher/src/hooks.ts | 69 - packages/graph-test-watcher/src/indexer.ts | 676 ------ packages/graph-test-watcher/src/job-runner.ts | 47 - packages/graph-test-watcher/src/resolvers.ts | 200 -- packages/graph-test-watcher/src/schema.gql | 144 -- packages/graph-test-watcher/src/server.ts | 42 - packages/graph-test-watcher/tsconfig.json | 74 - packages/mobymask-v2-watcher/.eslintignore | 2 - packages/mobymask-v2-watcher/.eslintrc.json | 28 - packages/mobymask-v2-watcher/README.md | 281 --- .../environments/local.toml | 76 - packages/mobymask-v2-watcher/indexing.md | 218 -- packages/mobymask-v2-watcher/package.json | 73 - .../src/artifacts/PhisherRegistry.json | 1934 ----------------- .../src/cli/checkpoint-cmds/create.ts | 33 - .../mobymask-v2-watcher/src/cli/checkpoint.ts | 39 - .../src/cli/export-state.ts | 27 - .../src/cli/import-state.ts | 28 - .../src/cli/index-block.ts | 27 - .../src/cli/inspect-cid.ts | 27 - packages/mobymask-v2-watcher/src/cli/peer.ts | 20 - .../src/cli/reset-cmds/job-queue.ts | 22 - .../src/cli/reset-cmds/state.ts | 24 - .../src/cli/reset-cmds/watcher.ts | 26 - packages/mobymask-v2-watcher/src/cli/reset.ts | 24 - .../src/cli/watch-contract.ts | 27 - packages/mobymask-v2-watcher/src/client.ts | 100 - packages/mobymask-v2-watcher/src/database.ts | 352 --- .../src/entity/BlockProgress.ts | 48 - .../src/entity/Contract.ts | 24 - .../mobymask-v2-watcher/src/entity/Event.ts | 38 - .../src/entity/IsMember.ts | 30 - .../src/entity/IsPhisher.ts | 30 - .../src/entity/IsRevoked.ts | 30 - .../src/entity/MultiNonce.ts | 34 - .../mobymask-v2-watcher/src/entity/State.ts | 36 - .../src/entity/StateSyncStatus.ts | 17 - .../src/entity/SyncStatus.ts | 36 - .../mobymask-v2-watcher/src/entity/_Owner.ts | 27 - packages/mobymask-v2-watcher/src/fill.ts | 32 - packages/mobymask-v2-watcher/src/gql/index.ts | 3 - .../src/gql/mutations/index.ts | 4 - .../src/gql/mutations/watchContract.gql | 3 - .../src/gql/queries/_owner.gql | 8 - .../src/gql/queries/events.gql | 40 - .../src/gql/queries/eventsInRange.gql | 40 - .../src/gql/queries/getState.gql | 15 - .../src/gql/queries/getStateByCID.gql | 15 - .../src/gql/queries/index.ts | 12 - .../src/gql/queries/isMember.gql | 8 - .../src/gql/queries/isPhisher.gql | 8 - .../src/gql/queries/isRevoked.gql | 8 - .../src/gql/queries/multiNonce.gql | 8 - .../src/gql/subscriptions/index.ts | 4 - .../src/gql/subscriptions/onEvent.gql | 40 - packages/mobymask-v2-watcher/src/hooks.ts | 129 -- packages/mobymask-v2-watcher/src/indexer.ts | 713 ------ .../mobymask-v2-watcher/src/job-runner.ts | 36 - .../mobymask-v2-watcher/src/libp2p-utils.ts | 149 -- packages/mobymask-v2-watcher/src/resolvers.ts | 160 -- packages/mobymask-v2-watcher/src/schema.gql | 117 - packages/mobymask-v2-watcher/src/server.ts | 43 - packages/mobymask-v2-watcher/src/types.ts | 3 - packages/mobymask-v2-watcher/tsconfig.json | 74 - packages/mobymask-watcher/.eslintignore | 2 - packages/mobymask-watcher/.eslintrc.json | 28 - packages/mobymask-watcher/README.md | 281 --- .../mobymask-watcher/environments/local.toml | 55 - packages/mobymask-watcher/indexing.md | 218 -- packages/mobymask-watcher/package.json | 71 - .../src/artifacts/PhisherRegistry.json | 1934 ----------------- .../src/cli/checkpoint-cmds/create.ts | 33 - .../mobymask-watcher/src/cli/checkpoint.ts | 39 - .../mobymask-watcher/src/cli/export-state.ts | 27 - .../mobymask-watcher/src/cli/import-state.ts | 28 - .../mobymask-watcher/src/cli/index-block.ts | 27 - .../mobymask-watcher/src/cli/inspect-cid.ts | 27 - .../src/cli/reset-cmds/job-queue.ts | 22 - .../src/cli/reset-cmds/state.ts | 24 - .../src/cli/reset-cmds/watcher.ts | 26 - packages/mobymask-watcher/src/cli/reset.ts | 24 - .../src/cli/watch-contract.ts | 27 - packages/mobymask-watcher/src/client.ts | 100 - packages/mobymask-watcher/src/database.ts | 352 --- .../src/entity/BlockProgress.ts | 48 - .../mobymask-watcher/src/entity/Contract.ts | 24 - packages/mobymask-watcher/src/entity/Event.ts | 38 - .../mobymask-watcher/src/entity/IsMember.ts | 30 - .../mobymask-watcher/src/entity/IsPhisher.ts | 30 - .../mobymask-watcher/src/entity/IsRevoked.ts | 30 - .../mobymask-watcher/src/entity/MultiNonce.ts | 34 - packages/mobymask-watcher/src/entity/State.ts | 36 - .../src/entity/StateSyncStatus.ts | 17 - .../mobymask-watcher/src/entity/SyncStatus.ts | 36 - .../mobymask-watcher/src/entity/_Owner.ts | 27 - packages/mobymask-watcher/src/fill.ts | 32 - packages/mobymask-watcher/src/gql/index.ts | 3 - .../src/gql/mutations/index.ts | 4 - .../src/gql/mutations/watchContract.gql | 3 - .../src/gql/queries/_owner.gql | 8 - .../src/gql/queries/events.gql | 40 - .../src/gql/queries/eventsInRange.gql | 40 - .../src/gql/queries/getState.gql | 15 - .../src/gql/queries/getStateByCID.gql | 15 - .../mobymask-watcher/src/gql/queries/index.ts | 12 - .../src/gql/queries/isMember.gql | 8 - .../src/gql/queries/isPhisher.gql | 8 - .../src/gql/queries/isRevoked.gql | 8 - .../src/gql/queries/multiNonce.gql | 8 - .../src/gql/subscriptions/index.ts | 4 - .../src/gql/subscriptions/onEvent.gql | 40 - packages/mobymask-watcher/src/hooks.ts | 129 -- packages/mobymask-watcher/src/indexer.ts | 668 ------ packages/mobymask-watcher/src/job-runner.ts | 36 - packages/mobymask-watcher/src/resolvers.ts | 160 -- packages/mobymask-watcher/src/schema.gql | 117 - packages/mobymask-watcher/src/server.ts | 31 - packages/mobymask-watcher/src/types.ts | 3 - packages/mobymask-watcher/tsconfig.json | 74 - packages/peer/package.json | 1 + packages/solidity-mapper/package.json | 1 + packages/test/package.json | 1 + packages/tracing-client/package.json | 1 + packages/util/package.json | 3 + yarn.lock | 39 +- 429 files changed, 23 insertions(+), 31044 deletions(-) delete mode 100644 packages/address-watcher/.eslintignore delete mode 100644 packages/address-watcher/.eslintrc.json delete mode 100644 packages/address-watcher/.gitignore delete mode 100644 packages/address-watcher/README.md delete mode 100644 packages/address-watcher/environments/local.toml delete mode 100644 packages/address-watcher/package.json delete mode 100644 packages/address-watcher/src/cli/watch-address.ts delete mode 100644 packages/address-watcher/src/database.ts delete mode 100644 packages/address-watcher/src/entity/Account.ts delete mode 100644 packages/address-watcher/src/entity/BlockProgress.ts delete mode 100644 packages/address-watcher/src/entity/Trace.ts delete mode 100644 packages/address-watcher/src/fill.ts delete mode 100644 packages/address-watcher/src/indexer.ts delete mode 100644 packages/address-watcher/src/job-runner.ts delete mode 100644 packages/address-watcher/src/resolvers.ts delete mode 100644 packages/address-watcher/src/schema.ts delete mode 100644 packages/address-watcher/src/server.ts delete mode 100644 packages/address-watcher/src/tx-watcher.ts delete mode 100644 packages/address-watcher/src/types/common/main.d.ts delete mode 100644 packages/address-watcher/src/types/common/package.json delete mode 100644 packages/address-watcher/src/util.test.ts delete mode 100644 packages/address-watcher/src/util.ts delete mode 100644 packages/address-watcher/tsconfig.json delete mode 100644 packages/eden-watcher/.eslintignore delete mode 100644 packages/eden-watcher/.eslintrc.json delete mode 100644 packages/eden-watcher/README.md delete mode 100644 packages/eden-watcher/codegen.yaml delete mode 100644 packages/eden-watcher/environments/local.toml delete mode 100644 packages/eden-watcher/package.json delete mode 100644 packages/eden-watcher/src/artifacts/DistributorGovernance.json delete mode 100644 packages/eden-watcher/src/artifacts/EdenNetwork.json delete mode 100644 packages/eden-watcher/src/artifacts/MerkleDistributor.json delete mode 100644 packages/eden-watcher/src/cli/checkpoint-cmds/create.ts delete mode 100644 packages/eden-watcher/src/cli/checkpoint-cmds/verify.ts delete mode 100644 packages/eden-watcher/src/cli/checkpoint.ts delete mode 100644 packages/eden-watcher/src/cli/export-state.ts delete mode 100644 packages/eden-watcher/src/cli/import-state.ts delete mode 100644 packages/eden-watcher/src/cli/index-block.ts delete mode 100644 packages/eden-watcher/src/cli/inspect-cid.ts delete mode 100644 packages/eden-watcher/src/cli/reset-cmds/job-queue.ts delete mode 100644 packages/eden-watcher/src/cli/reset-cmds/state.ts delete mode 100644 packages/eden-watcher/src/cli/reset-cmds/watcher.ts delete mode 100644 packages/eden-watcher/src/cli/reset.ts delete mode 100644 packages/eden-watcher/src/cli/watch-contract.ts delete mode 100644 packages/eden-watcher/src/client.ts delete mode 100644 packages/eden-watcher/src/database.ts delete mode 100644 packages/eden-watcher/src/entity/Account.ts delete mode 100644 packages/eden-watcher/src/entity/Block.ts delete mode 100644 packages/eden-watcher/src/entity/BlockProgress.ts delete mode 100644 packages/eden-watcher/src/entity/Claim.ts delete mode 100644 packages/eden-watcher/src/entity/Contract.ts delete mode 100644 packages/eden-watcher/src/entity/Distribution.ts delete mode 100644 packages/eden-watcher/src/entity/Distributor.ts delete mode 100644 packages/eden-watcher/src/entity/Epoch.ts delete mode 100644 packages/eden-watcher/src/entity/Event.ts delete mode 100644 packages/eden-watcher/src/entity/FrothyEntity.ts delete mode 100644 packages/eden-watcher/src/entity/Network.ts delete mode 100644 packages/eden-watcher/src/entity/Producer.ts delete mode 100644 packages/eden-watcher/src/entity/ProducerEpoch.ts delete mode 100644 packages/eden-watcher/src/entity/ProducerRewardCollectorChange.ts delete mode 100644 packages/eden-watcher/src/entity/ProducerSet.ts delete mode 100644 packages/eden-watcher/src/entity/ProducerSetChange.ts delete mode 100644 packages/eden-watcher/src/entity/RewardSchedule.ts delete mode 100644 packages/eden-watcher/src/entity/RewardScheduleEntry.ts delete mode 100644 packages/eden-watcher/src/entity/Slash.ts delete mode 100644 packages/eden-watcher/src/entity/Slot.ts delete mode 100644 packages/eden-watcher/src/entity/SlotClaim.ts delete mode 100644 packages/eden-watcher/src/entity/Staker.ts delete mode 100644 packages/eden-watcher/src/entity/State.ts delete mode 100644 packages/eden-watcher/src/entity/StateSyncStatus.ts delete mode 100644 packages/eden-watcher/src/entity/Subscriber.ts delete mode 100644 packages/eden-watcher/src/entity/SyncStatus.ts delete mode 100644 packages/eden-watcher/src/fill.ts delete mode 100644 packages/eden-watcher/src/gql/index.ts delete mode 100644 packages/eden-watcher/src/gql/mutations/index.ts delete mode 100644 packages/eden-watcher/src/gql/mutations/watchContract.gql delete mode 100644 packages/eden-watcher/src/gql/queries/account.gql delete mode 100644 packages/eden-watcher/src/gql/queries/block.gql delete mode 100644 packages/eden-watcher/src/gql/queries/claim.gql delete mode 100644 packages/eden-watcher/src/gql/queries/distribution.gql delete mode 100644 packages/eden-watcher/src/gql/queries/distributor.gql delete mode 100644 packages/eden-watcher/src/gql/queries/epoch.gql delete mode 100644 packages/eden-watcher/src/gql/queries/events.gql delete mode 100644 packages/eden-watcher/src/gql/queries/eventsInRange.gql delete mode 100644 packages/eden-watcher/src/gql/queries/getState.gql delete mode 100644 packages/eden-watcher/src/gql/queries/getStateByCID.gql delete mode 100644 packages/eden-watcher/src/gql/queries/index.ts delete mode 100644 packages/eden-watcher/src/gql/queries/network.gql delete mode 100644 packages/eden-watcher/src/gql/queries/producer.gql delete mode 100644 packages/eden-watcher/src/gql/queries/producerEpoch.gql delete mode 100644 packages/eden-watcher/src/gql/queries/producerRewardCollectorChange.gql delete mode 100644 packages/eden-watcher/src/gql/queries/producerSet.gql delete mode 100644 packages/eden-watcher/src/gql/queries/producerSetChange.gql delete mode 100644 packages/eden-watcher/src/gql/queries/rewardSchedule.gql delete mode 100644 packages/eden-watcher/src/gql/queries/rewardScheduleEntry.gql delete mode 100644 packages/eden-watcher/src/gql/queries/slash.gql delete mode 100644 packages/eden-watcher/src/gql/queries/slot.gql delete mode 100644 packages/eden-watcher/src/gql/queries/slotClaim.gql delete mode 100644 packages/eden-watcher/src/gql/queries/staker.gql delete mode 100644 packages/eden-watcher/src/gql/subscriptions/index.ts delete mode 100644 packages/eden-watcher/src/gql/subscriptions/onEvent.gql delete mode 100644 packages/eden-watcher/src/hooks.ts delete mode 100644 packages/eden-watcher/src/indexer.ts delete mode 100644 packages/eden-watcher/src/job-runner.ts delete mode 100644 packages/eden-watcher/src/resolvers.ts delete mode 100644 packages/eden-watcher/src/schema.gql delete mode 100644 packages/eden-watcher/src/server.ts delete mode 100644 packages/eden-watcher/test/queries/account.gql delete mode 100644 packages/eden-watcher/test/queries/block.gql delete mode 100644 packages/eden-watcher/test/queries/claim.gql delete mode 100644 packages/eden-watcher/test/queries/distribution.gql delete mode 100644 packages/eden-watcher/test/queries/distributor.gql delete mode 100644 packages/eden-watcher/test/queries/epoch.gql delete mode 100644 packages/eden-watcher/test/queries/network.gql delete mode 100644 packages/eden-watcher/test/queries/producer.gql delete mode 100644 packages/eden-watcher/test/queries/producerEpoch.gql delete mode 100644 packages/eden-watcher/test/queries/producerRewardCollectorChange.gql delete mode 100644 packages/eden-watcher/test/queries/producerSet.gql delete mode 100644 packages/eden-watcher/test/queries/producerSetChange.gql delete mode 100644 packages/eden-watcher/test/queries/rewardSchedule.gql delete mode 100644 packages/eden-watcher/test/queries/rewardScheduleEntry.gql delete mode 100644 packages/eden-watcher/test/queries/slash.gql delete mode 100644 packages/eden-watcher/test/queries/slot.gql delete mode 100644 packages/eden-watcher/test/queries/slotClaim.gql delete mode 100644 packages/eden-watcher/test/queries/staker.gql delete mode 100644 packages/eden-watcher/tsconfig.json delete mode 100644 packages/erc20-watcher/.eslintignore delete mode 100644 packages/erc20-watcher/.eslintrc.json delete mode 100644 packages/erc20-watcher/.gitignore delete mode 100644 packages/erc20-watcher/README.md delete mode 100644 packages/erc20-watcher/environments/local.toml delete mode 100644 packages/erc20-watcher/hardhat.config.ts delete mode 100644 packages/erc20-watcher/package.json delete mode 100644 packages/erc20-watcher/src/artifacts/ERC20.json delete mode 100644 packages/erc20-watcher/src/artifacts/ERC20NameBytes.json delete mode 100644 packages/erc20-watcher/src/artifacts/ERC20SymbolBytes.json delete mode 100644 packages/erc20-watcher/src/cli/reset-cmds/job-queue.ts delete mode 100644 packages/erc20-watcher/src/cli/reset-cmds/state.ts delete mode 100644 packages/erc20-watcher/src/cli/reset-cmds/watcher.ts delete mode 100644 packages/erc20-watcher/src/cli/reset.ts delete mode 100644 packages/erc20-watcher/src/cli/watch-contract.ts delete mode 100644 packages/erc20-watcher/src/client.ts delete mode 100644 packages/erc20-watcher/src/database.ts delete mode 100644 packages/erc20-watcher/src/entity/Allowance.ts delete mode 100644 packages/erc20-watcher/src/entity/Balance.ts delete mode 100644 packages/erc20-watcher/src/entity/BlockProgress.ts delete mode 100644 packages/erc20-watcher/src/entity/Contract.ts delete mode 100644 packages/erc20-watcher/src/entity/Event.ts delete mode 100644 packages/erc20-watcher/src/entity/State.ts delete mode 100644 packages/erc20-watcher/src/entity/StateSyncStatus.ts delete mode 100644 packages/erc20-watcher/src/entity/SyncStatus.ts delete mode 100644 packages/erc20-watcher/src/fill.ts delete mode 100644 packages/erc20-watcher/src/index.ts delete mode 100644 packages/erc20-watcher/src/indexer.ts delete mode 100644 packages/erc20-watcher/src/job-runner.ts delete mode 100644 packages/erc20-watcher/src/queries.ts delete mode 100644 packages/erc20-watcher/src/resolvers.ts delete mode 100644 packages/erc20-watcher/src/schema.ts delete mode 100644 packages/erc20-watcher/src/server.ts delete mode 100644 packages/erc20-watcher/src/types/common/main.d.ts delete mode 100644 packages/erc20-watcher/src/types/common/package.json delete mode 100644 packages/erc20-watcher/src/utils/index.ts delete mode 100644 packages/erc20-watcher/src/utils/static-token-definition.ts delete mode 100644 packages/erc20-watcher/test/contracts/GLDToken.sol delete mode 100644 packages/erc20-watcher/test/tasks/account.ts delete mode 100644 packages/erc20-watcher/test/tasks/block-latest.ts delete mode 100644 packages/erc20-watcher/test/tasks/token-approve.ts delete mode 100644 packages/erc20-watcher/test/tasks/token-deploy.ts delete mode 100644 packages/erc20-watcher/test/tasks/token-transfer-from.ts delete mode 100644 packages/erc20-watcher/test/tasks/token-transfer.ts delete mode 100644 packages/erc20-watcher/tsconfig.json delete mode 100644 packages/erc721-watcher/.eslintignore delete mode 100644 packages/erc721-watcher/.eslintrc.json delete mode 100644 packages/erc721-watcher/.gitignore delete mode 100644 packages/erc721-watcher/README.md delete mode 100644 packages/erc721-watcher/environments/local.toml delete mode 100644 packages/erc721-watcher/hardhat.config.ts delete mode 100644 packages/erc721-watcher/package.json delete mode 100644 packages/erc721-watcher/src/artifacts/ERC721.json delete mode 100644 packages/erc721-watcher/src/cli/checkpoint-cmds/create.ts delete mode 100644 packages/erc721-watcher/src/cli/checkpoint.ts delete mode 100644 packages/erc721-watcher/src/cli/export-state.ts delete mode 100644 packages/erc721-watcher/src/cli/import-state.ts delete mode 100644 packages/erc721-watcher/src/cli/index-block.ts delete mode 100644 packages/erc721-watcher/src/cli/inspect-cid.ts delete mode 100644 packages/erc721-watcher/src/cli/reset-cmds/job-queue.ts delete mode 100644 packages/erc721-watcher/src/cli/reset-cmds/state.ts delete mode 100644 packages/erc721-watcher/src/cli/reset-cmds/watcher.ts delete mode 100644 packages/erc721-watcher/src/cli/reset.ts delete mode 100644 packages/erc721-watcher/src/cli/watch-contract.ts delete mode 100644 packages/erc721-watcher/src/client.ts delete mode 100644 packages/erc721-watcher/src/database.ts delete mode 100644 packages/erc721-watcher/src/entity/BalanceOf.ts delete mode 100644 packages/erc721-watcher/src/entity/BlockProgress.ts delete mode 100644 packages/erc721-watcher/src/entity/Contract.ts delete mode 100644 packages/erc721-watcher/src/entity/Event.ts delete mode 100644 packages/erc721-watcher/src/entity/GetApproved.ts delete mode 100644 packages/erc721-watcher/src/entity/IsApprovedForAll.ts delete mode 100644 packages/erc721-watcher/src/entity/Name.ts delete mode 100644 packages/erc721-watcher/src/entity/OwnerOf.ts delete mode 100644 packages/erc721-watcher/src/entity/State.ts delete mode 100644 packages/erc721-watcher/src/entity/StateSyncStatus.ts delete mode 100644 packages/erc721-watcher/src/entity/SupportsInterface.ts delete mode 100644 packages/erc721-watcher/src/entity/Symbol.ts delete mode 100644 packages/erc721-watcher/src/entity/SyncStatus.ts delete mode 100644 packages/erc721-watcher/src/entity/TokenURI.ts delete mode 100644 packages/erc721-watcher/src/entity/TransferCount.ts delete mode 100644 packages/erc721-watcher/src/entity/_Balances.ts delete mode 100644 packages/erc721-watcher/src/entity/_Name.ts delete mode 100644 packages/erc721-watcher/src/entity/_OperatorApprovals.ts delete mode 100644 packages/erc721-watcher/src/entity/_Owners.ts delete mode 100644 packages/erc721-watcher/src/entity/_Symbol.ts delete mode 100644 packages/erc721-watcher/src/entity/_TokenApprovals.ts delete mode 100644 packages/erc721-watcher/src/fill.ts delete mode 100644 packages/erc721-watcher/src/gql/index.ts delete mode 100644 packages/erc721-watcher/src/gql/mutations/index.ts delete mode 100644 packages/erc721-watcher/src/gql/mutations/watchContract.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/_balances.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/_name.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/_operatorApprovals.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/_owners.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/_symbol.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/_tokenApprovals.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/balanceOf.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/events.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/eventsInRange.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/getApproved.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/getState.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/getStateByCID.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/index.ts delete mode 100644 packages/erc721-watcher/src/gql/queries/isApprovedForAll.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/name.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/ownerOf.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/supportsInterface.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/symbol.gql delete mode 100644 packages/erc721-watcher/src/gql/queries/tokenURI.gql delete mode 100644 packages/erc721-watcher/src/gql/subscriptions/index.ts delete mode 100644 packages/erc721-watcher/src/gql/subscriptions/onEvent.gql delete mode 100644 packages/erc721-watcher/src/hooks.ts delete mode 100644 packages/erc721-watcher/src/indexer.ts delete mode 100644 packages/erc721-watcher/src/job-runner.ts delete mode 100644 packages/erc721-watcher/src/resolvers.ts delete mode 100644 packages/erc721-watcher/src/schema.gql delete mode 100644 packages/erc721-watcher/src/server.ts delete mode 100644 packages/erc721-watcher/test/contracts/TestNFT.sol delete mode 100644 packages/erc721-watcher/test/tasks/account.ts delete mode 100644 packages/erc721-watcher/test/tasks/block-latest.ts delete mode 100644 packages/erc721-watcher/test/tasks/nft-deploy.ts delete mode 100644 packages/erc721-watcher/test/tasks/nft-mint.ts delete mode 100644 packages/erc721-watcher/test/tasks/nft-transfer.ts delete mode 100644 packages/erc721-watcher/tsconfig.json delete mode 100644 packages/graph-test-watcher/.eslintignore delete mode 100644 packages/graph-test-watcher/.eslintrc.json delete mode 100644 packages/graph-test-watcher/.gitignore delete mode 100644 packages/graph-test-watcher/README.md delete mode 100644 packages/graph-test-watcher/environments/local.toml delete mode 100644 packages/graph-test-watcher/package.json delete mode 100644 packages/graph-test-watcher/src/artifacts/Example.json delete mode 100644 packages/graph-test-watcher/src/cli/checkpoint-cmds/create.ts delete mode 100644 packages/graph-test-watcher/src/cli/checkpoint-cmds/verify.ts delete mode 100644 packages/graph-test-watcher/src/cli/checkpoint.ts delete mode 100644 packages/graph-test-watcher/src/cli/export-state.ts delete mode 100644 packages/graph-test-watcher/src/cli/import-state.ts delete mode 100644 packages/graph-test-watcher/src/cli/index-block.ts delete mode 100644 packages/graph-test-watcher/src/cli/inspect-cid.ts delete mode 100644 packages/graph-test-watcher/src/cli/reset-cmds/job-queue.ts delete mode 100644 packages/graph-test-watcher/src/cli/reset-cmds/state.ts delete mode 100644 packages/graph-test-watcher/src/cli/reset-cmds/watcher.ts delete mode 100644 packages/graph-test-watcher/src/cli/reset.ts delete mode 100644 packages/graph-test-watcher/src/cli/watch-contract.ts delete mode 100644 packages/graph-test-watcher/src/client.ts delete mode 100644 packages/graph-test-watcher/src/database.ts delete mode 100644 packages/graph-test-watcher/src/entity/Author.ts delete mode 100644 packages/graph-test-watcher/src/entity/BlockProgress.ts delete mode 100644 packages/graph-test-watcher/src/entity/Blog.ts delete mode 100644 packages/graph-test-watcher/src/entity/Category.ts delete mode 100644 packages/graph-test-watcher/src/entity/Contract.ts delete mode 100644 packages/graph-test-watcher/src/entity/Event.ts delete mode 100644 packages/graph-test-watcher/src/entity/FrothyEntity.ts delete mode 100644 packages/graph-test-watcher/src/entity/GetMethod.ts delete mode 100644 packages/graph-test-watcher/src/entity/State.ts delete mode 100644 packages/graph-test-watcher/src/entity/StateSyncStatus.ts delete mode 100644 packages/graph-test-watcher/src/entity/Subscriber.ts delete mode 100644 packages/graph-test-watcher/src/entity/SyncStatus.ts delete mode 100644 packages/graph-test-watcher/src/entity/_Test.ts delete mode 100644 packages/graph-test-watcher/src/fill.ts delete mode 100644 packages/graph-test-watcher/src/gql/index.ts delete mode 100644 packages/graph-test-watcher/src/gql/mutations/index.ts delete mode 100644 packages/graph-test-watcher/src/gql/mutations/watchContract.gql delete mode 100644 packages/graph-test-watcher/src/gql/queries/_test.gql delete mode 100644 packages/graph-test-watcher/src/gql/queries/author.gql delete mode 100644 packages/graph-test-watcher/src/gql/queries/blog.gql delete mode 100644 packages/graph-test-watcher/src/gql/queries/category.gql delete mode 100644 packages/graph-test-watcher/src/gql/queries/events.gql delete mode 100644 packages/graph-test-watcher/src/gql/queries/eventsInRange.gql delete mode 100644 packages/graph-test-watcher/src/gql/queries/getMethod.gql delete mode 100644 packages/graph-test-watcher/src/gql/queries/getState.gql delete mode 100644 packages/graph-test-watcher/src/gql/queries/getStateByCID.gql delete mode 100644 packages/graph-test-watcher/src/gql/queries/index.ts delete mode 100644 packages/graph-test-watcher/src/gql/subscriptions/index.ts delete mode 100644 packages/graph-test-watcher/src/gql/subscriptions/onEvent.gql delete mode 100644 packages/graph-test-watcher/src/hooks.ts delete mode 100644 packages/graph-test-watcher/src/indexer.ts delete mode 100644 packages/graph-test-watcher/src/job-runner.ts delete mode 100644 packages/graph-test-watcher/src/resolvers.ts delete mode 100644 packages/graph-test-watcher/src/schema.gql delete mode 100644 packages/graph-test-watcher/src/server.ts delete mode 100644 packages/graph-test-watcher/tsconfig.json delete mode 100644 packages/mobymask-v2-watcher/.eslintignore delete mode 100644 packages/mobymask-v2-watcher/.eslintrc.json delete mode 100644 packages/mobymask-v2-watcher/README.md delete mode 100644 packages/mobymask-v2-watcher/environments/local.toml delete mode 100644 packages/mobymask-v2-watcher/indexing.md delete mode 100644 packages/mobymask-v2-watcher/package.json delete mode 100644 packages/mobymask-v2-watcher/src/artifacts/PhisherRegistry.json delete mode 100644 packages/mobymask-v2-watcher/src/cli/checkpoint-cmds/create.ts delete mode 100644 packages/mobymask-v2-watcher/src/cli/checkpoint.ts delete mode 100644 packages/mobymask-v2-watcher/src/cli/export-state.ts delete mode 100644 packages/mobymask-v2-watcher/src/cli/import-state.ts delete mode 100644 packages/mobymask-v2-watcher/src/cli/index-block.ts delete mode 100644 packages/mobymask-v2-watcher/src/cli/inspect-cid.ts delete mode 100644 packages/mobymask-v2-watcher/src/cli/peer.ts delete mode 100644 packages/mobymask-v2-watcher/src/cli/reset-cmds/job-queue.ts delete mode 100644 packages/mobymask-v2-watcher/src/cli/reset-cmds/state.ts delete mode 100644 packages/mobymask-v2-watcher/src/cli/reset-cmds/watcher.ts delete mode 100644 packages/mobymask-v2-watcher/src/cli/reset.ts delete mode 100644 packages/mobymask-v2-watcher/src/cli/watch-contract.ts delete mode 100644 packages/mobymask-v2-watcher/src/client.ts delete mode 100644 packages/mobymask-v2-watcher/src/database.ts delete mode 100644 packages/mobymask-v2-watcher/src/entity/BlockProgress.ts delete mode 100644 packages/mobymask-v2-watcher/src/entity/Contract.ts delete mode 100644 packages/mobymask-v2-watcher/src/entity/Event.ts delete mode 100644 packages/mobymask-v2-watcher/src/entity/IsMember.ts delete mode 100644 packages/mobymask-v2-watcher/src/entity/IsPhisher.ts delete mode 100644 packages/mobymask-v2-watcher/src/entity/IsRevoked.ts delete mode 100644 packages/mobymask-v2-watcher/src/entity/MultiNonce.ts delete mode 100644 packages/mobymask-v2-watcher/src/entity/State.ts delete mode 100644 packages/mobymask-v2-watcher/src/entity/StateSyncStatus.ts delete mode 100644 packages/mobymask-v2-watcher/src/entity/SyncStatus.ts delete mode 100644 packages/mobymask-v2-watcher/src/entity/_Owner.ts delete mode 100644 packages/mobymask-v2-watcher/src/fill.ts delete mode 100644 packages/mobymask-v2-watcher/src/gql/index.ts delete mode 100644 packages/mobymask-v2-watcher/src/gql/mutations/index.ts delete mode 100644 packages/mobymask-v2-watcher/src/gql/mutations/watchContract.gql delete mode 100644 packages/mobymask-v2-watcher/src/gql/queries/_owner.gql delete mode 100644 packages/mobymask-v2-watcher/src/gql/queries/events.gql delete mode 100644 packages/mobymask-v2-watcher/src/gql/queries/eventsInRange.gql delete mode 100644 packages/mobymask-v2-watcher/src/gql/queries/getState.gql delete mode 100644 packages/mobymask-v2-watcher/src/gql/queries/getStateByCID.gql delete mode 100644 packages/mobymask-v2-watcher/src/gql/queries/index.ts delete mode 100644 packages/mobymask-v2-watcher/src/gql/queries/isMember.gql delete mode 100644 packages/mobymask-v2-watcher/src/gql/queries/isPhisher.gql delete mode 100644 packages/mobymask-v2-watcher/src/gql/queries/isRevoked.gql delete mode 100644 packages/mobymask-v2-watcher/src/gql/queries/multiNonce.gql delete mode 100644 packages/mobymask-v2-watcher/src/gql/subscriptions/index.ts delete mode 100644 packages/mobymask-v2-watcher/src/gql/subscriptions/onEvent.gql delete mode 100644 packages/mobymask-v2-watcher/src/hooks.ts delete mode 100644 packages/mobymask-v2-watcher/src/indexer.ts delete mode 100644 packages/mobymask-v2-watcher/src/job-runner.ts delete mode 100644 packages/mobymask-v2-watcher/src/libp2p-utils.ts delete mode 100644 packages/mobymask-v2-watcher/src/resolvers.ts delete mode 100644 packages/mobymask-v2-watcher/src/schema.gql delete mode 100644 packages/mobymask-v2-watcher/src/server.ts delete mode 100644 packages/mobymask-v2-watcher/src/types.ts delete mode 100644 packages/mobymask-v2-watcher/tsconfig.json delete mode 100644 packages/mobymask-watcher/.eslintignore delete mode 100644 packages/mobymask-watcher/.eslintrc.json delete mode 100644 packages/mobymask-watcher/README.md delete mode 100644 packages/mobymask-watcher/environments/local.toml delete mode 100644 packages/mobymask-watcher/indexing.md delete mode 100644 packages/mobymask-watcher/package.json delete mode 100644 packages/mobymask-watcher/src/artifacts/PhisherRegistry.json delete mode 100644 packages/mobymask-watcher/src/cli/checkpoint-cmds/create.ts delete mode 100644 packages/mobymask-watcher/src/cli/checkpoint.ts delete mode 100644 packages/mobymask-watcher/src/cli/export-state.ts delete mode 100644 packages/mobymask-watcher/src/cli/import-state.ts delete mode 100644 packages/mobymask-watcher/src/cli/index-block.ts delete mode 100644 packages/mobymask-watcher/src/cli/inspect-cid.ts delete mode 100644 packages/mobymask-watcher/src/cli/reset-cmds/job-queue.ts delete mode 100644 packages/mobymask-watcher/src/cli/reset-cmds/state.ts delete mode 100644 packages/mobymask-watcher/src/cli/reset-cmds/watcher.ts delete mode 100644 packages/mobymask-watcher/src/cli/reset.ts delete mode 100644 packages/mobymask-watcher/src/cli/watch-contract.ts delete mode 100644 packages/mobymask-watcher/src/client.ts delete mode 100644 packages/mobymask-watcher/src/database.ts delete mode 100644 packages/mobymask-watcher/src/entity/BlockProgress.ts delete mode 100644 packages/mobymask-watcher/src/entity/Contract.ts delete mode 100644 packages/mobymask-watcher/src/entity/Event.ts delete mode 100644 packages/mobymask-watcher/src/entity/IsMember.ts delete mode 100644 packages/mobymask-watcher/src/entity/IsPhisher.ts delete mode 100644 packages/mobymask-watcher/src/entity/IsRevoked.ts delete mode 100644 packages/mobymask-watcher/src/entity/MultiNonce.ts delete mode 100644 packages/mobymask-watcher/src/entity/State.ts delete mode 100644 packages/mobymask-watcher/src/entity/StateSyncStatus.ts delete mode 100644 packages/mobymask-watcher/src/entity/SyncStatus.ts delete mode 100644 packages/mobymask-watcher/src/entity/_Owner.ts delete mode 100644 packages/mobymask-watcher/src/fill.ts delete mode 100644 packages/mobymask-watcher/src/gql/index.ts delete mode 100644 packages/mobymask-watcher/src/gql/mutations/index.ts delete mode 100644 packages/mobymask-watcher/src/gql/mutations/watchContract.gql delete mode 100644 packages/mobymask-watcher/src/gql/queries/_owner.gql delete mode 100644 packages/mobymask-watcher/src/gql/queries/events.gql delete mode 100644 packages/mobymask-watcher/src/gql/queries/eventsInRange.gql delete mode 100644 packages/mobymask-watcher/src/gql/queries/getState.gql delete mode 100644 packages/mobymask-watcher/src/gql/queries/getStateByCID.gql delete mode 100644 packages/mobymask-watcher/src/gql/queries/index.ts delete mode 100644 packages/mobymask-watcher/src/gql/queries/isMember.gql delete mode 100644 packages/mobymask-watcher/src/gql/queries/isPhisher.gql delete mode 100644 packages/mobymask-watcher/src/gql/queries/isRevoked.gql delete mode 100644 packages/mobymask-watcher/src/gql/queries/multiNonce.gql delete mode 100644 packages/mobymask-watcher/src/gql/subscriptions/index.ts delete mode 100644 packages/mobymask-watcher/src/gql/subscriptions/onEvent.gql delete mode 100644 packages/mobymask-watcher/src/hooks.ts delete mode 100644 packages/mobymask-watcher/src/indexer.ts delete mode 100644 packages/mobymask-watcher/src/job-runner.ts delete mode 100644 packages/mobymask-watcher/src/resolvers.ts delete mode 100644 packages/mobymask-watcher/src/schema.gql delete mode 100644 packages/mobymask-watcher/src/server.ts delete mode 100644 packages/mobymask-watcher/src/types.ts delete mode 100644 packages/mobymask-watcher/tsconfig.json diff --git a/packages/address-watcher/.eslintignore b/packages/address-watcher/.eslintignore deleted file mode 100644 index 653874b5..00000000 --- a/packages/address-watcher/.eslintignore +++ /dev/null @@ -1,5 +0,0 @@ -# Don't lint node_modules. -node_modules - -# Don't lint build output. -dist diff --git a/packages/address-watcher/.eslintrc.json b/packages/address-watcher/.eslintrc.json deleted file mode 100644 index a2b842c2..00000000 --- a/packages/address-watcher/.eslintrc.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "env": { - "browser": true, - "es2021": true - }, - "extends": [ - "semistandard", - "plugin:@typescript-eslint/recommended" - ], - "parser": "@typescript-eslint/parser", - "parserOptions": { - "ecmaVersion": 12, - "sourceType": "module" - }, - "plugins": [ - "@typescript-eslint" - ], - "rules": { - "indent": ["error", 2, { "SwitchCase": 1 }], - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/explicit-module-boundary-types": [ - "warn", - { - "allowArgumentsExplicitlyTypedAsAny": true - } - ] - } -} diff --git a/packages/address-watcher/.gitignore b/packages/address-watcher/.gitignore deleted file mode 100644 index b3ab1ae4..00000000 --- a/packages/address-watcher/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -.idea/ -.vscode/ -node_modules/ -build/ -tmp/ -temp/ \ No newline at end of file diff --git a/packages/address-watcher/README.md b/packages/address-watcher/README.md deleted file mode 100644 index 5fc3f747..00000000 --- a/packages/address-watcher/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# Address Watcher - -## Setup - -First try the [stack orchestrator](https://github.com/cerc-io/stack-orchestrator) to quickly get started. Advanced users can see [here](/docs/README.md) for instructions on setting up a local environment by hand. - -Build files: - -```bash -yarn && yarn build -``` - -## Run - -Run the following commands in different terminals: - -GraphQL server: - -```bash -yarn server -``` - -Job runner for processing the tracing requests queue: - -```bash -yarn job-runner -``` - -To fill a block range: - -```bash -yarn fill --start-block 1 --end-block 1000 -``` diff --git a/packages/address-watcher/environments/local.toml b/packages/address-watcher/environments/local.toml deleted file mode 100644 index 363b83ff..00000000 --- a/packages/address-watcher/environments/local.toml +++ /dev/null @@ -1,28 +0,0 @@ -[server] - host = "127.0.0.1" - port = 3002 - -[database] - type = "postgres" - host = "localhost" - port = 5432 - database = "address-watcher" - username = "postgres" - password = "postgres" - synchronize = true - logging = false - -[upstream] - traceProviderEndpoint = "http://127.0.0.1:8545" - - [upstream.ethServer] - gqlApiEndpoint = "http://127.0.0.1:8082/graphql" - - [upstream.cache] - name = "requests" - enabled = false - deleteOnStart = false - -[jobQueue] - dbConnectionString = "postgres://postgres:postgres@localhost/address-watcher-job-queue" - maxCompletionLagInSecs = 300 diff --git a/packages/address-watcher/package.json b/packages/address-watcher/package.json deleted file mode 100644 index f7337e9e..00000000 --- a/packages/address-watcher/package.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "name": "@cerc-io/address-watcher", - "version": "0.2.38", - "description": "Address Watcher", - "private": true, - "scripts": { - "lint": "eslint .", - "test": "mocha -r ts-node/register src/**/*.test.ts", - "build": "tsc", - "server": "DEBUG=vulcanize:* node --enable-source-maps dist/server.js", - "server:dev": "DEBUG=vulcanize:* nodemon --watch src src/server.ts", - "job-runner": "DEBUG=vulcanize:* node --enable-source-maps dist/job-runner.js", - "job-runner:dev": "DEBUG=vulcanize:* nodemon --watch src src/job-runner.ts", - "fill": "DEBUG=vulcanize:* node --enable-source-maps dist/fill.js", - "fill:dev": "DEBUG=vulcanize:* ts-node src/fill.ts" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/cerc-io/watcher-ts.git" - }, - "author": "", - "license": "AGPL-3.0", - "bugs": { - "url": "https://github.com/cerc-io/watcher-ts/issues" - }, - "homepage": "https://github.com/cerc-io/watcher-ts#readme", - "dependencies": { - "@apollo/client": "^3.3.19", - "@cerc-io/cache": "^0.2.38", - "@cerc-io/ipld-eth-client": "^0.2.38", - "@cerc-io/solidity-mapper": "^0.2.38", - "@cerc-io/tracing-client": "^0.2.38", - "@cerc-io/util": "^0.2.38", - "@types/lodash": "^4.14.168", - "debug": "^4.3.1", - "ethers": "^5.4.4", - "express": "^4.18.2", - "graphql": "^15.5.0", - "lodash": "^4.17.21", - "reflect-metadata": "^0.1.13", - "typeorm": "^0.2.32", - "typeorm-naming-strategies": "^2.0.0", - "yargs": "^17.0.1" - }, - "devDependencies": { - "@ethersproject/abi": "^5.3.0", - "@types/chai": "^4.2.19", - "@types/express": "^4.17.14", - "@types/mocha": "^8.2.2", - "@types/yargs": "^17.0.0", - "@typescript-eslint/eslint-plugin": "^5.47.1", - "@typescript-eslint/parser": "^5.47.1", - "chai": "^4.3.4", - "eslint": "^8.35.0", - "eslint-config-semistandard": "^15.0.1", - "eslint-config-standard": "^16.0.3", - "eslint-plugin-import": "^2.27.5", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-promise": "^5.1.0", - "eslint-plugin-standard": "^5.0.0", - "mocha": "^8.4.0", - "nodemon": "^2.0.7" - } -} diff --git a/packages/address-watcher/src/cli/watch-address.ts b/packages/address-watcher/src/cli/watch-address.ts deleted file mode 100644 index c77a9071..00000000 --- a/packages/address-watcher/src/cli/watch-address.ts +++ /dev/null @@ -1,51 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import yargs from 'yargs'; -import 'reflect-metadata'; -import { ethers } from 'ethers'; - -import { Config, DEFAULT_CONFIG_PATH, getConfig } from '@cerc-io/util'; - -import { Database } from '../database'; - -(async () => { - const argv = await yargs.parserConfiguration({ - 'parse-numbers': false - }).options({ - configFile: { - type: 'string', - require: true, - demandOption: true, - describe: 'configuration file path (toml)', - default: DEFAULT_CONFIG_PATH - }, - address: { - type: 'string', - require: true, - demandOption: true, - describe: 'Address to watch' - }, - startingBlock: { - type: 'number', - default: 1, - describe: 'Starting block' - } - }).argv; - - const config: Config = await getConfig(argv.configFile); - const { database: dbConfig } = config; - - assert(dbConfig); - - const db = new Database(dbConfig); - await db.init(); - - // Always use the checksum address (https://docs.ethers.io/v5/api/utils/address/#utils-getAddress). - const address = ethers.utils.getAddress(argv.address); - - await db.saveAccount(address, argv.startingBlock); - await db.close(); -})(); diff --git a/packages/address-watcher/src/database.ts b/packages/address-watcher/src/database.ts deleted file mode 100644 index 1e1a0484..00000000 --- a/packages/address-watcher/src/database.ts +++ /dev/null @@ -1,141 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import { Connection, ConnectionOptions, createConnection, DeepPartial } from 'typeorm'; -import { SnakeNamingStrategy } from 'typeorm-naming-strategies'; -import path from 'path'; - -import { Account } from './entity/Account'; -import { BlockProgress } from './entity/BlockProgress'; -import { Trace } from './entity/Trace'; - -export class Database { - _config: ConnectionOptions; - _conn!: Connection; - - constructor (config: ConnectionOptions) { - assert(config); - - this._config = { - ...config, - entities: [path.join(__dirname, 'entity/*')] - }; - } - - async init (): Promise { - assert(!this._conn); - - this._conn = await createConnection({ - ...this._config, - namingStrategy: new SnakeNamingStrategy() - }); - } - - async close (): Promise { - return this._conn.close(); - } - - async isWatchedAddress (address: string): Promise { - const numRows = await this._conn.getRepository(Account) - .createQueryBuilder() - .where('address = :address', { address }) - .getCount(); - - return numRows > 0; - } - - async saveAccount (address: string, startingBlock: number): Promise { - await this._conn.transaction(async (tx) => { - const repo = tx.getRepository(Account); - - const numRows = await repo - .createQueryBuilder() - .where('address = :address', { address }) - .getCount(); - - if (numRows === 0) { - const entity = repo.create({ address, startingBlock }); - await repo.save(entity); - } - }); - } - - async getAccount (address: string): Promise { - return this._conn.getRepository(Account) - .createQueryBuilder() - .where('address = :address', { address }) - .getOne(); - } - - async getTrace (txHash: string): Promise { - const repo = this._conn.getRepository(Trace); - return repo.findOne({ where: { txHash } }); - } - - async saveTrace ({ txHash, blockNumber, blockHash, trace }: DeepPartial): Promise { - await this._conn.transaction(async (tx) => { - const repo = tx.getRepository(Trace); - - const numRows = await repo - .createQueryBuilder() - .where('tx_hash = :txHash', { txHash }) - .getCount(); - - if (numRows === 0) { - const entity = repo.create({ txHash, blockNumber, blockHash, trace }); - await repo.save(entity); - } - }); - } - - async saveTraceEntity (trace: Trace): Promise { - const repo = this._conn.getRepository(Trace); - return repo.save(trace); - } - - async getAppearances (address: string, fromBlockNumber: number, toBlockNumber: number): Promise { - return this._conn.getRepository(Trace) - .createQueryBuilder('trace') - .leftJoinAndSelect('trace.accounts', 'account') - .where('address = :address AND block_number >= :fromBlockNumber AND block_number <= :toBlockNumber', { address, fromBlockNumber, toBlockNumber }) - .orderBy({ block_number: 'ASC' }) - .getMany(); - } - - async getBlockProgress (blockHash: string): Promise { - const repo = this._conn.getRepository(BlockProgress); - return repo.findOne({ where: { blockHash } }); - } - - async initBlockProgress (blockHash: string, blockNumber: number, numTx: number): Promise { - await this._conn.transaction(async (tx) => { - const repo = tx.getRepository(BlockProgress); - - const numRows = await repo - .createQueryBuilder() - .where('block_hash = :blockHash', { blockHash }) - .getCount(); - - if (numRows === 0) { - const entity = repo.create({ blockHash, blockNumber, numTx, numTracedTx: 0, isComplete: (numTx === 0) }); - await repo.save(entity); - } - }); - } - - async updateBlockProgress (blockHash: string): Promise { - await this._conn.transaction(async (tx) => { - const repo = tx.getRepository(BlockProgress); - const entity = await repo.findOne({ where: { blockHash } }); - if (entity && !entity.isComplete) { - entity.numTracedTx++; - if (entity.numTracedTx >= entity.numTx) { - entity.isComplete = true; - } - await repo.save(entity); - } - }); - } -} diff --git a/packages/address-watcher/src/entity/Account.ts b/packages/address-watcher/src/entity/Account.ts deleted file mode 100644 index 9ff4c5eb..00000000 --- a/packages/address-watcher/src/entity/Account.ts +++ /dev/null @@ -1,19 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, ManyToMany, JoinTable } from 'typeorm'; -import { Trace } from './Trace'; - -@Entity() -export class Account { - @PrimaryColumn('varchar', { length: 42 }) - address!: string; - - @Column('integer') - startingBlock!: number; - - @ManyToMany(() => Trace, trace => trace.accounts) - @JoinTable() - appearances: Trace[]; -} diff --git a/packages/address-watcher/src/entity/BlockProgress.ts b/packages/address-watcher/src/entity/BlockProgress.ts deleted file mode 100644 index 4c08c88c..00000000 --- a/packages/address-watcher/src/entity/BlockProgress.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockNumber']) -export class BlockProgress { - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('integer') - numTx!: number; - - @Column('integer') - numTracedTx!: number; - - @Column('boolean') - isComplete!: boolean; -} diff --git a/packages/address-watcher/src/entity/Trace.ts b/packages/address-watcher/src/entity/Trace.ts deleted file mode 100644 index 736a677b..00000000 --- a/packages/address-watcher/src/entity/Trace.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index, ManyToMany } from 'typeorm'; - -import { Account } from './Account'; - -@Entity() -@Index(['txHash'], { unique: true }) -@Index(['blockNumber']) -export class Trace { - @PrimaryColumn('varchar', { length: 66 }) - txHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('text') - trace!: string; - - @ManyToMany(() => Account, account => account.appearances, { eager: true, cascade: ['insert'] }) - accounts: Account[]; -} diff --git a/packages/address-watcher/src/fill.ts b/packages/address-watcher/src/fill.ts deleted file mode 100644 index 154f619f..00000000 --- a/packages/address-watcher/src/fill.ts +++ /dev/null @@ -1,108 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import 'reflect-metadata'; -import yargs from 'yargs'; -import { hideBin } from 'yargs/helpers'; -import debug from 'debug'; - -import { getCache } from '@cerc-io/cache'; -import { EthClient } from '@cerc-io/ipld-eth-client'; -import { Config, DEFAULT_CONFIG_PATH, getConfig, JobQueue } from '@cerc-io/util'; - -import { Database } from './database'; -import { QUEUE_TX_TRACING } from './tx-watcher'; - -const log = debug('vulcanize:server'); - -export const main = async (): Promise => { - const argv = await yargs(hideBin(process.argv)).parserConfiguration({ - 'parse-numbers': false - }).options({ - configFile: { - alias: 'f', - type: 'string', - require: true, - demandOption: true, - describe: 'configuration file path (toml)', - default: DEFAULT_CONFIG_PATH - }, - startBlock: { - type: 'number', - require: true, - demandOption: true, - describe: 'Block number to start processing at' - }, - endBlock: { - type: 'number', - require: true, - demandOption: true, - describe: 'Block number to stop processing at' - } - }).argv; - - const config = await getConfig(argv.configFile); - - assert(config.server, 'Missing server config'); - - const { upstream, database: dbConfig, jobQueue: jobQueueConfig } = config; - - assert(dbConfig, 'Missing database config'); - - const db = new Database(dbConfig); - await db.init(); - - assert(upstream, 'Missing upstream config'); - const { ethServer: { gqlApiEndpoint }, traceProviderEndpoint, cache: cacheConfig } = upstream; - assert(gqlApiEndpoint, 'Missing upstream ethServer.gqlApiEndpoint'); - assert(traceProviderEndpoint, 'Missing upstream traceProviderEndpoint'); - - const cache = await getCache(cacheConfig); - const ethClient = new EthClient({ - gqlEndpoint: gqlApiEndpoint, - cache - }); - - assert(jobQueueConfig, 'Missing job queue config'); - - const { dbConnectionString, maxCompletionLagInSecs } = jobQueueConfig; - assert(dbConnectionString, 'Missing job queue db connection string'); - - const jobQueue = new JobQueue({ dbConnectionString, maxCompletionLag: maxCompletionLagInSecs }); - await jobQueue.start(); - - for (let blockNumber = argv.startBlock; blockNumber <= argv.endBlock; blockNumber++) { - log(`Fill block ${blockNumber}`); - - // TODO: Add pause between requests so as to not overwhelm the upsteam server. - const result = await ethClient.getBlockWithTransactions({ blockNumber }); - const { allEthHeaderCids: { nodes: blockNodes } } = result; - for (let bi = 0; bi < blockNodes.length; bi++) { - const { blockHash, ethTransactionCidsByHeaderId: { nodes: txNodes } } = blockNodes[bi]; - const blockProgress = await db.getBlockProgress(blockHash); - if (blockProgress) { - log(`Block number ${blockNumber}, block hash ${blockHash} already known, skip filling`); - } else { - await db.initBlockProgress(blockHash, blockNumber, txNodes.length); - - for (let ti = 0; ti < txNodes.length; ti++) { - const { txHash } = txNodes[ti]; - log(`Filling block number ${blockNumber}, block hash ${blockHash}, tx hash ${txHash}`); - - // Never push appearances from fill jobs to GQL subscribers, as this command can be run multiple times - // for the same block range, and/or process the same block in multiple different runs spread over a - // period of time. Also, the tx's are probably too old anyway for publishing. - await jobQueue.pushJob(QUEUE_TX_TRACING, { txHash, blockHash, publish: false, publishBlockProgress: true }); - } - } - } - } -}; - -main().then(() => { - process.exit(); -}).catch(err => { - log(err); -}); diff --git a/packages/address-watcher/src/indexer.ts b/packages/address-watcher/src/indexer.ts deleted file mode 100644 index f9a0c5ae..00000000 --- a/packages/address-watcher/src/indexer.ts +++ /dev/null @@ -1,111 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import debug from 'debug'; -import { ethers } from 'ethers'; - -import { EthClient } from '@cerc-io/ipld-eth-client'; -import { GetStorageAt } from '@cerc-io/solidity-mapper'; -import { TracingClient } from '@cerc-io/tracing-client'; - -import { addressesInTrace } from './util'; -import { Database } from './database'; -import { Trace } from './entity/Trace'; -import { Account } from './entity/Account'; -import { BlockProgress } from './entity/BlockProgress'; - -const log = debug('vulcanize:indexer'); - -export class Indexer { - _db: Database; - _ethClient: EthClient; - _getStorageAt: GetStorageAt; - _tracingClient: TracingClient; - - constructor (db: Database, ethClient: EthClient, tracingClient: TracingClient) { - assert(db); - assert(ethClient); - assert(tracingClient); - - this._db = db; - this._ethClient = ethClient; - this._tracingClient = tracingClient; - this._getStorageAt = this._ethClient.getStorageAt.bind(this._ethClient); - } - - async isWatchedAddress (address : string): Promise { - assert(address); - - return this._db.isWatchedAddress(ethers.utils.getAddress(address)); - } - - async watchAddress (address: string, startingBlock: number): Promise { - // Always use the checksum address (https://docs.ethers.io/v5/api/utils/address/#utils-getAddress). - await this._db.saveAccount(ethers.utils.getAddress(address), startingBlock); - - return true; - } - - async getTrace (txHash: string): Promise { - return this._db.getTrace(txHash); - } - - async traceTxAndIndexAppearances (txHash: string): Promise { - let entity = await this._db.getTrace(txHash); - if (entity) { - log(`traceTx: db hit ${txHash}`); - } else { - log(`traceTx: db miss, fetching from tracing API server ${txHash}`); - - const tx = await this._tracingClient.getTx(txHash); - const trace = await this._tracingClient.getTxTrace(txHash, 'callTraceWithAddresses', '15s'); - - await this._db.saveTrace({ - txHash, - blockNumber: tx.blockNumber, - blockHash: tx.blockHash, - trace: JSON.stringify(trace) - }); - - entity = await this._db.getTrace(txHash); - - assert(entity); - await this._indexAppearances(entity); - } - - return entity; - } - - async getAppearances (address: string, fromBlockNumber: number, toBlockNumber: number): Promise { - return this._db.getAppearances(address, fromBlockNumber, toBlockNumber); - } - - async getBlockProgress (blockHash: string): Promise { - return this._db.getBlockProgress(blockHash); - } - - async updateBlockProgress (blockHash: string): Promise { - return this._db.updateBlockProgress(blockHash); - } - - async _indexAppearances (trace: Trace): Promise { - const traceObj = JSON.parse(trace.trace); - - // TODO: Check if tx has failed? - const addresses = addressesInTrace(traceObj); - - trace.accounts = addresses.map((address: string) => { - assert(address); - - const account = new Account(); - account.address = ethers.utils.getAddress(address); - account.startingBlock = trace.blockNumber; - - return account; - }); - - return await this._db.saveTraceEntity(trace); - } -} diff --git a/packages/address-watcher/src/job-runner.ts b/packages/address-watcher/src/job-runner.ts deleted file mode 100644 index 704c65a5..00000000 --- a/packages/address-watcher/src/job-runner.ts +++ /dev/null @@ -1,78 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import 'reflect-metadata'; -import yargs from 'yargs'; -import { hideBin } from 'yargs/helpers'; -import debug from 'debug'; - -import { getCache } from '@cerc-io/cache'; -import { EthClient } from '@cerc-io/ipld-eth-client'; -import { TracingClient } from '@cerc-io/tracing-client'; -import { getConfig, JobQueue, DEFAULT_CONFIG_PATH, Config } from '@cerc-io/util'; - -import { Indexer } from './indexer'; -import { Database } from './database'; -import { QUEUE_TX_TRACING } from './tx-watcher'; - -const log = debug('vulcanize:server'); - -export const main = async (): Promise => { - const argv = await yargs(hideBin(process.argv)) - .option('f', { - alias: 'config-file', - demandOption: true, - describe: 'configuration file path (toml)', - type: 'string', - default: DEFAULT_CONFIG_PATH - }) - .argv; - - const config: Config = await getConfig(argv.f); - - assert(config.server, 'Missing server config'); - - const { upstream, database: dbConfig, jobQueue: jobQueueConfig } = config; - - assert(dbConfig, 'Missing database config'); - - const db = new Database(dbConfig); - await db.init(); - - assert(upstream, 'Missing upstream config'); - const { ethServer: { gqlApiEndpoint }, traceProviderEndpoint, cache: cacheConfig } = upstream; - assert(gqlApiEndpoint, 'Missing upstream ethServer.gqlApiEndpoint'); - assert(traceProviderEndpoint, 'Missing upstream traceProviderEndpoint'); - - const cache = await getCache(cacheConfig); - const ethClient = new EthClient({ - gqlEndpoint: gqlApiEndpoint, - cache - }); - - const tracingClient = new TracingClient(traceProviderEndpoint); - - const indexer = new Indexer(db, ethClient, tracingClient); - - assert(jobQueueConfig, 'Missing job queue config'); - - const { dbConnectionString, maxCompletionLagInSecs } = jobQueueConfig; - assert(dbConnectionString, 'Missing job queue db connection string'); - - const jobQueue = new JobQueue({ dbConnectionString, maxCompletionLag: maxCompletionLagInSecs }); - await jobQueue.start(); - - await jobQueue.subscribe(QUEUE_TX_TRACING, async (job) => { - const { data: { txHash } } = job; - await indexer.traceTxAndIndexAppearances(txHash); - await jobQueue.markComplete(job); - }); -}; - -main().then(() => { - log('Starting job runner...'); -}).catch(err => { - log(err); -}); diff --git a/packages/address-watcher/src/resolvers.ts b/packages/address-watcher/src/resolvers.ts deleted file mode 100644 index 9aa98f5b..00000000 --- a/packages/address-watcher/src/resolvers.ts +++ /dev/null @@ -1,73 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import debug from 'debug'; -import { withFilter } from 'graphql-subscriptions'; -import { ethers } from 'ethers'; - -import { Indexer } from './indexer'; -import { TxWatcher } from './tx-watcher'; - -const log = debug('vulcanize:resolver'); - -interface WatchAddressParams { - address: string, - startingBlock: number -} - -interface AppearanceParams { - address: string, - fromBlockNumber: number, - toBlockNumber: number -} - -export const createResolvers = async (indexer: Indexer, txWatcher: TxWatcher): Promise => { - return { - Subscription: { - onAddressEvent: { - subscribe: withFilter( - () => txWatcher.getAddressEventIterator(), - (payload: any, variables: any) => { - return payload.onAddressEvent.address === ethers.utils.getAddress(variables.address); - } - ) - }, - - onBlockProgressEvent: { - subscribe: () => txWatcher.getBlockProgressEventIterator() - } - }, - - Mutation: { - watchAddress: (_: any, { address, startingBlock = 1 }: WatchAddressParams): Promise => { - address = ethers.utils.getAddress(address); - - log('watchAddress', address, startingBlock); - return indexer.watchAddress(address, startingBlock); - } - }, - - Query: { - appearances: async (_: any, { address, fromBlockNumber, toBlockNumber }: AppearanceParams): Promise => { - address = ethers.utils.getAddress(address); - - log('appearances', address, fromBlockNumber, toBlockNumber); - return indexer.getAppearances(address, fromBlockNumber, toBlockNumber); - }, - - traceTx: async (_: any, { txHash }: { txHash: string }): Promise => { - log('traceTx', txHash); - - const { blockHash, blockNumber, trace } = await indexer.traceTxAndIndexAppearances(txHash); - - return { - txHash, - blockNumber, - blockHash, - trace - }; - } - } - }; -}; diff --git a/packages/address-watcher/src/schema.ts b/packages/address-watcher/src/schema.ts deleted file mode 100644 index 85fe6a3a..00000000 --- a/packages/address-watcher/src/schema.ts +++ /dev/null @@ -1,79 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { gql } from '@apollo/client/core'; - -export default gql` -# Types - -type TxTrace { - txHash: String! - blockNumber: Int! - blockHash: String! - trace: String! -} - -# Watched address event, include additional context over and above the event data. -type WatchedAddressEvent { - address: String! - txTrace: TxTrace! -} - -type BlockProgressEvent { - blockNumber: Int! - blockHash: String! - numTx: Int! - numTracedTx: Int! - isComplete: Boolean! -} - -# -# Queries -# - -type Query { - - # - # Developer API methods - # - - appearances( - address: String! - fromBlockNumber: Int! - toBlockNumber: Int! - ): [TxTrace!] - - # - # Low level utility methods - # - - traceTx( - txHash: String! - ): TxTrace -} - -# -# Subscriptions -# -type Subscription { - - # Watch for address events (at head of chain). - onAddressEvent(address: String!): WatchedAddressEvent! - - # Watch for block progress events from filler process. - onBlockProgressEvent: BlockProgressEvent! -} - -# -# Mutations -# -type Mutation { - - # Actively watch and index data for the address. - watchAddress( - address: String! - startingBlock: Int - ): Boolean! -} -`; diff --git a/packages/address-watcher/src/server.ts b/packages/address-watcher/src/server.ts deleted file mode 100644 index 0979a149..00000000 --- a/packages/address-watcher/src/server.ts +++ /dev/null @@ -1,92 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import 'reflect-metadata'; -import express, { Application } from 'express'; -import { PubSub } from 'graphql-subscriptions'; -import yargs from 'yargs'; -import { hideBin } from 'yargs/helpers'; -import debug from 'debug'; - -import { getCache } from '@cerc-io/cache'; -import { EthClient } from '@cerc-io/ipld-eth-client'; -import { TracingClient } from '@cerc-io/tracing-client'; -import { getConfig, JobQueue, DEFAULT_CONFIG_PATH, createAndStartServer, Config } from '@cerc-io/util'; - -import typeDefs from './schema'; - -import { createResolvers } from './resolvers'; -import { Indexer } from './indexer'; -import { Database } from './database'; -import { TxWatcher } from './tx-watcher'; - -const log = debug('vulcanize:server'); - -export const main = async (): Promise => { - const argv = await yargs(hideBin(process.argv)) - .option('f', { - alias: 'config-file', - demandOption: true, - describe: 'configuration file path (toml)', - type: 'string', - default: DEFAULT_CONFIG_PATH - }) - .argv; - - const config: Config = await getConfig(argv.f); - - assert(config.server, 'Missing server config'); - - const { upstream, database: dbConfig, jobQueue: jobQueueConfig } = config; - - assert(dbConfig, 'Missing database config'); - - const db = new Database(dbConfig); - await db.init(); - - assert(upstream, 'Missing upstream config'); - const { ethServer: { gqlApiEndpoint }, traceProviderEndpoint, cache: cacheConfig } = upstream; - assert(gqlApiEndpoint, 'Missing upstream ethServer.gqlApiEndpoint'); - assert(traceProviderEndpoint, 'Missing upstream traceProviderEndpoint'); - - const cache = await getCache(cacheConfig); - const ethClient = new EthClient({ - gqlEndpoint: gqlApiEndpoint, - cache - }); - - const tracingClient = new TracingClient(traceProviderEndpoint); - - const indexer = new Indexer(db, ethClient, tracingClient); - - assert(jobQueueConfig, 'Missing job queue config'); - - const { dbConnectionString, maxCompletionLagInSecs } = jobQueueConfig; - assert(dbConnectionString, 'Missing job queue db connection string'); - assert(dbConnectionString, 'Missing job queue max completion lag time (seconds)'); - - const jobQueue = new JobQueue({ dbConnectionString, maxCompletionLag: maxCompletionLagInSecs }); - await jobQueue.start(); - - // Note: In-memory pubsub works fine for now, as each watcher is a single process anyway. - // Later: https://www.apollographql.com/docs/apollo-server/data/subscriptions/#production-pubsub-libraries - const pubsub = new PubSub(); - const txWatcher = new TxWatcher(ethClient, indexer, pubsub, jobQueue); - await txWatcher.start(); - - const resolvers = await createResolvers(indexer, txWatcher); - - // Create an Express app - const app: Application = express(); - const server = createAndStartServer(app, typeDefs, resolvers, config.server); - - return { app, server }; -}; - -main().then(() => { - log('Starting server...'); -}).catch(err => { - log(err); -}); diff --git a/packages/address-watcher/src/tx-watcher.ts b/packages/address-watcher/src/tx-watcher.ts deleted file mode 100644 index 0b23a9da..00000000 --- a/packages/address-watcher/src/tx-watcher.ts +++ /dev/null @@ -1,126 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import debug from 'debug'; -import { PubSub } from 'graphql-subscriptions'; - -import { EthClient } from '@cerc-io/ipld-eth-client'; -import { JobQueue } from '@cerc-io/util'; - -import { Indexer } from './indexer'; -import { BlockProgress } from './entity/BlockProgress'; - -const log = debug('vulcanize:tx-watcher'); - -export const AddressEvent = 'address-event'; -export const BlockProgressEvent = 'block-progress-event'; -export const QUEUE_TX_TRACING = 'tx-tracing'; - -export class TxWatcher { - _ethClient: EthClient; - _indexer: Indexer; - _pubsub: PubSub; - _watchTxSubscription: ZenObservable.Subscription | undefined; - _jobQueue: JobQueue; - - constructor (ethClient: EthClient, indexer: Indexer, pubsub: PubSub, jobQueue: JobQueue) { - this._ethClient = ethClient; - this._indexer = indexer; - this._pubsub = pubsub; - this._jobQueue = jobQueue; - } - - getAddressEventIterator (): AsyncIterator { - return this._pubsub.asyncIterator([AddressEvent]); - } - - getBlockProgressEventIterator (): AsyncIterator { - return this._pubsub.asyncIterator([BlockProgressEvent]); - } - - async start (): Promise { - assert(!this._watchTxSubscription, 'subscription already started'); - - log('Started watching upstream tx...'); - - this._jobQueue.onComplete(QUEUE_TX_TRACING, async (job) => { - const { data: { request, failed, state, createdOn } } = job; - - await this._indexer.updateBlockProgress(request.data.blockHash); - const blockProgress = await this._indexer.getBlockProgress(request.data.blockHash); - if (blockProgress && request.data.publishBlockProgress) { - await this.publishBlockProgressToSubscribers(blockProgress); - } - - const timeElapsedInSeconds = (Date.now() - Date.parse(createdOn)) / 1000; - log(`Job onComplete tx ${request.data.txHash} publish ${!!request.data.publish}`); - if (!failed && state === 'completed' && request.data.publish) { - // Check for max acceptable lag time between tracing request and sending results to live subscribers. - if (timeElapsedInSeconds <= this._jobQueue.maxCompletionLag) { - return await this.publishAddressEventToSubscribers(request.data.txHash, timeElapsedInSeconds); - } else { - log(`tx ${request.data.txHash} is too old (${timeElapsedInSeconds}s), not broadcasting to live subscribers`); - } - } - }); - - // TODO: Update to pull based watcher. - // this._watchTxSubscription = await this._ethClient.watchTransactions(async (value) => { - // const { txHash, ethHeaderCidByHeaderId: { blockHash, blockNumber } } = _.get(value, 'data.listen.relatedNode'); - // log('watchTransaction', JSON.stringify({ txHash, blockHash, blockNumber }, null, 2)); - // await this._jobQueue.pushJob(QUEUE_TX_TRACING, { txHash, blockHash, publish: true }); - // }); - } - - async publishAddressEventToSubscribers (txHash: string, timeElapsedInSeconds: number): Promise { - const traceObj = await this._indexer.getTrace(txHash); - if (!traceObj) { - return; - } - - const { blockNumber, blockHash, trace } = traceObj; - - for (let i = 0; i < traceObj.accounts.length; i++) { - const account = traceObj.accounts[i]; - - log(`publishing trace for ${txHash} (${timeElapsedInSeconds}s elapsed) to GQL subscribers for address ${account.address}`); - - // Publishing the event here will result in pushing the payload to GQL subscribers for `onAddressEvent(address)`. - await this._pubsub.publish(AddressEvent, { - onAddressEvent: { - address: account.address, - txTrace: { - txHash, - blockHash, - blockNumber, - trace - } - } - }); - } - } - - async publishBlockProgressToSubscribers (blockProgress: BlockProgress): Promise { - const { blockHash, blockNumber, numTx, numTracedTx, isComplete } = blockProgress; - - // Publishing the event here will result in pushing the payload to GQL subscribers for `onAddressEvent(address)`. - await this._pubsub.publish(BlockProgressEvent, { - onBlockProgressEvent: { - blockHash, - blockNumber, - numTx, - numTracedTx, - isComplete - } - }); - } - - async stop (): Promise { - if (this._watchTxSubscription) { - log('Stopped watching upstream tx'); - this._watchTxSubscription.unsubscribe(); - } - } -} diff --git a/packages/address-watcher/src/types/common/main.d.ts b/packages/address-watcher/src/types/common/main.d.ts deleted file mode 100644 index ceaf2626..00000000 --- a/packages/address-watcher/src/types/common/main.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -// https://medium.com/@steveruiz/using-a-javascript-library-without-type-declarations-in-a-typescript-project-3643490015f3 -declare module 'canonical-json' -declare module 'lodash-contrib'; diff --git a/packages/address-watcher/src/types/common/package.json b/packages/address-watcher/src/types/common/package.json deleted file mode 100644 index 5861d0f0..00000000 --- a/packages/address-watcher/src/types/common/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "common", - "version": "0.1.0", - "license": "AGPL-3.0", - "typings": "main.d.ts" -} diff --git a/packages/address-watcher/src/util.test.ts b/packages/address-watcher/src/util.test.ts deleted file mode 100644 index 3470bff0..00000000 --- a/packages/address-watcher/src/util.test.ts +++ /dev/null @@ -1,150 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { describe, it } from 'mocha'; -import { expect } from 'chai'; - -import { addressesInTrace } from './util'; - -describe('addressInTrace', () => { - it('should parse an empty trace', () => { - const addresses = addressesInTrace({}); - expect(addresses).to.eql([]); - }); - - it('should parse an unnested trace', () => { - const addresses = addressesInTrace({ - from: '0xDC7d7A8920C8Eecc098da5B7522a5F31509b5Bfc', - to: '0xCA6D29232D1435D8198E3E5302495417dD073d61' - }); - - expect(addresses).to.eql([ - '0xCA6D29232D1435D8198E3E5302495417dD073d61', - '0xDC7d7A8920C8Eecc098da5B7522a5F31509b5Bfc' - ]); - }); - - it('should parse an unnested trace with an addresses field', () => { - const addresses = addressesInTrace({ - from: '0xDC7d7A8920C8Eecc098da5B7522a5F31509b5Bfc', - to: '0xCA6D29232D1435D8198E3E5302495417dD073d61', - addresses: { - '0x9273D9437B0bf2F1b7999d8dB72960d6379564d1': {}, - '0xd86fB467B78901310e9967A2C8B601A5E794c12C': {} - } - }); - - expect(addresses).to.eql([ - '0x9273D9437B0bf2F1b7999d8dB72960d6379564d1', - '0xCA6D29232D1435D8198E3E5302495417dD073d61', - '0xDC7d7A8920C8Eecc098da5B7522a5F31509b5Bfc', - '0xd86fB467B78901310e9967A2C8B601A5E794c12C' - ]); - }); - - it('should parse a nested trace', () => { - const addresses = addressesInTrace({ - from: '0xDC7d7A8920C8Eecc098da5B7522a5F31509b5Bfc', - to: '0xCA6D29232D1435D8198E3E5302495417dD073d61', - calls: [{ - from: '0x9273D9437B0bf2F1b7999d8dB72960d6379564d1', - to: '0xd86fB467B78901310e9967A2C8B601A5E794c12C' - }, - { - from: '0xf29340ca4ad7A797dF2d67Be58d354EC284AE62f', - to: '0xEcFF6b14D3ed9569108b413f846279E64E39BC92' - }] - }); - - expect(addresses).to.eql([ - '0x9273D9437B0bf2F1b7999d8dB72960d6379564d1', - '0xCA6D29232D1435D8198E3E5302495417dD073d61', - '0xDC7d7A8920C8Eecc098da5B7522a5F31509b5Bfc', - '0xEcFF6b14D3ed9569108b413f846279E64E39BC92', - '0xd86fB467B78901310e9967A2C8B601A5E794c12C', - '0xf29340ca4ad7A797dF2d67Be58d354EC284AE62f' - ]); - }); - - it('should parse a nested trace with an addresses field', () => { - const addresses = addressesInTrace({ - from: '0xDC7d7A8920C8Eecc098da5B7522a5F31509b5Bfc', - to: '0xCA6D29232D1435D8198E3E5302495417dD073d61', - calls: [{ - from: '0x9273D9437B0bf2F1b7999d8dB72960d6379564d1', - to: '0xd86fB467B78901310e9967A2C8B601A5E794c12C', - addresses: { - '0xf29340ca4ad7A797dF2d67Be58d354EC284AE62f': {}, - '0xEcFF6b14D3ed9569108b413f846279E64E39BC92': {} - } - }] - }); - - expect(addresses).to.eql([ - '0x9273D9437B0bf2F1b7999d8dB72960d6379564d1', - '0xCA6D29232D1435D8198E3E5302495417dD073d61', - '0xDC7d7A8920C8Eecc098da5B7522a5F31509b5Bfc', - '0xEcFF6b14D3ed9569108b413f846279E64E39BC92', - '0xd86fB467B78901310e9967A2C8B601A5E794c12C', - '0xf29340ca4ad7A797dF2d67Be58d354EC284AE62f' - ]); - }); - - it('should not return duplicate addresses', () => { - const addresses = addressesInTrace({ - from: '0xDC7d7A8920C8Eecc098da5B7522a5F31509b5Bfc', - to: '0xCA6D29232D1435D8198E3E5302495417dD073d61', - calls: [{ - from: '0xDC7d7A8920C8Eecc098da5B7522a5F31509b5Bfc', - to: '0xCA6D29232D1435D8198E3E5302495417dD073d61', - addresses: { - '0xDC7d7A8920C8Eecc098da5B7522a5F31509b5Bfc': {}, - '0xCA6D29232D1435D8198E3E5302495417dD073d61': {} - } - }] - }); - - expect(addresses).to.eql([ - '0xCA6D29232D1435D8198E3E5302495417dD073d61', - '0xDC7d7A8920C8Eecc098da5B7522a5F31509b5Bfc' - ]); - }); - - it('should return correct addresses for an ERC20 transfer', () => { - /* eslint-disable */ - const trace = { - "type": "CALL", - "from": "0xdc7d7a8920c8eecc098da5b7522a5f31509b5bfc", - "to": "0x1ca7c995f8ef0a2989bbce08d5b7efe50a584aa1", - "value": "0x0", - "gas": "0x4edf", - "gasUsed": "0x3982", - "input": "0xa9059cbb000000000000000000000000ca6d29232d1435d8198e3e5302495417dd073d610000000000000000000000000000000000000000000000000de0b6b3a7640000", - "output": "0x0000000000000000000000000000000000000000000000000000000000000001", - "time": "66.609994ms", - "addresses": { - "0xca6d29232d1435d8198e3e5302495417dd073d61": { - "confidence": 1, - "opcodes": [ - "CALLDATALOAD", "AND", "SWAP1", "DUP5", "DUP3", "AND", "DUP4", "POP", "DUP6", "AND", "AND", "DUP5", "AND", "AND", "DUP2", "AND", "POP", "SWAP2" - ] - }, - "0xdc7d7a8920c8eecc098da5b7522a5f31509b5bfc": { - "confidence": 1, - "opcodes": [ - "CALLER", "POP", "JUMP", "JUMPDEST", "DUP4", "AND", "DUP4", "POP", "DUP8", "AND", "AND", "DUP6", "AND", "AND", "DUP4", "AND", "POP" - ] - } - } - }; - /* eslint-enable */ - - const addresses = addressesInTrace(trace); - expect(addresses).to.eql([ - '0x1ca7c995f8eF0A2989BbcE08D5B7Efe50A584aa1', - '0xCA6D29232D1435D8198E3E5302495417dD073d61', - '0xDC7d7A8920C8Eecc098da5B7522a5F31509b5Bfc' - ]); - }); -}); diff --git a/packages/address-watcher/src/util.ts b/packages/address-watcher/src/util.ts deleted file mode 100644 index 9c2fb56b..00000000 --- a/packages/address-watcher/src/util.ts +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import _ from 'lodash'; -import { ethers } from 'ethers'; - -export const addressesInTrace = (obj: any): any => { - return _.uniq(_.compact(_.flattenDeep(addressesIn(obj)))) - .sort() - .map(address => ethers.utils.getAddress(address)); -}; - -const addressesIn = (obj: any): any => { - const addresses: any = []; - - if (obj) { - addresses.push(obj.from); - addresses.push(obj.to); - - if (obj.addresses) { - addresses.push(_.keys(obj.addresses)); - } - - if (obj.calls) { - obj.calls.forEach((call: any) => { - addresses.push(addressesIn(call)); - }); - } - } - - return addresses; -}; diff --git a/packages/address-watcher/tsconfig.json b/packages/address-watcher/tsconfig.json deleted file mode 100644 index e19a1b30..00000000 --- a/packages/address-watcher/tsconfig.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "compilerOptions": { - /* Visit https://aka.ms/tsconfig.json to read more about this file */ - - /* Basic Options */ - // "incremental": true, /* Enable incremental compilation */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ - "lib": [ "ES5", "ES6", "ES2020" ], /* Specify library files to be included in the compilation. */ - // "allowJs": true, /* Allow javascript files to be compiled. */ - // "checkJs": true, /* Report errors in .js files. */ - // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ - "declaration": true, /* Generates corresponding '.d.ts' file. */ - // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - "sourceMap": true, /* Generates corresponding '.map' file. */ - // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "dist", /* Redirect output structure to the directory. */ - // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - // "composite": true, /* Enable project compilation */ - // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ - // "removeComments": true, /* Do not emit comments to output. */ - // "noEmit": true, /* Do not emit outputs. */ - // "importHelpers": true, /* Import emit helpers from 'tslib'. */ - "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ - // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* Enable strict null checks. */ - // "strictFunctionTypes": true, /* Enable strict checking of function types. */ - // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ - "strictPropertyInitialization": false, /* Enable strict checking of property initialization in classes. */ - // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - - /* Additional Checks */ - // "noUnusedLocals": true, /* Report errors on unused locals. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ - - /* Module Resolution Options */ - "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ - // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ - // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ - "typeRoots": [ - "./src/types" - ], /* List of folders to include type definitions from. */ - // "types": [], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ - // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - - /* Source Map Options */ - // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ - // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - - /* Experimental Options */ - "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ - // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - - /* Advanced Options */ - "skipLibCheck": true, /* Skip type checking of declaration files. */ - "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ - "resolveJsonModule": true /* Enabling the option allows importing JSON, and validating the types in that JSON file. */ - }, - "include": ["src"], - "exclude": ["dist", "src/**/*.test.ts"] -} diff --git a/packages/cli/package.json b/packages/cli/package.json index 263a5f59..ec212333 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -28,8 +28,10 @@ "devDependencies": { "@types/express": "^4.17.14", "@types/node": "16.11.7", + "@types/yargs": "^17.0.0", "@typescript-eslint/eslint-plugin": "^5.47.1", "@typescript-eslint/parser": "^5.47.1", + "copyfiles": "^2.4.1", "eslint-config-semistandard": "^15.0.1", "eslint-config-standard": "^5.0.0", "eslint-plugin-import": "^2.27.5", diff --git a/packages/codegen/package.json b/packages/codegen/package.json index f51b8867..74a78bcc 100644 --- a/packages/codegen/package.json +++ b/packages/codegen/package.json @@ -40,7 +40,9 @@ "devDependencies": { "@openzeppelin/contracts": "^4.3.2", "@types/js-yaml": "^4.0.3", + "@types/lodash": "^4.14.168", "@types/node": "^16.9.0", + "@types/yargs": "^17.0.0", "@typescript-eslint/eslint-plugin": "^5.47.1", "@typescript-eslint/parser": "^5.47.1", "eslint": "^8.35.0", diff --git a/packages/eden-watcher/.eslintignore b/packages/eden-watcher/.eslintignore deleted file mode 100644 index 55cb5225..00000000 --- a/packages/eden-watcher/.eslintignore +++ /dev/null @@ -1,2 +0,0 @@ -# Don't lint build output. -dist diff --git a/packages/eden-watcher/.eslintrc.json b/packages/eden-watcher/.eslintrc.json deleted file mode 100644 index a2b842c2..00000000 --- a/packages/eden-watcher/.eslintrc.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "env": { - "browser": true, - "es2021": true - }, - "extends": [ - "semistandard", - "plugin:@typescript-eslint/recommended" - ], - "parser": "@typescript-eslint/parser", - "parserOptions": { - "ecmaVersion": 12, - "sourceType": "module" - }, - "plugins": [ - "@typescript-eslint" - ], - "rules": { - "indent": ["error", 2, { "SwitchCase": 1 }], - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/explicit-module-boundary-types": [ - "warn", - { - "allowArgumentsExplicitlyTypedAsAny": true - } - ] - } -} diff --git a/packages/eden-watcher/README.md b/packages/eden-watcher/README.md deleted file mode 100644 index 30ef1628..00000000 --- a/packages/eden-watcher/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# EdenNetwork Watcher - -## Setup - -First try the [stack orchestrator](https://github.com/cerc-io/stack-orchestrator) to quickly get started. Advanced users can see [here](/docs/README.md) for instructions on setting up a local environment by hand. - - -## Run - -Setup with: - -```bash -yarn && yarn build -``` - -then checkout the [CLI guide](/docs/cli.md) for examples of commands that can be run on this watcher. diff --git a/packages/eden-watcher/codegen.yaml b/packages/eden-watcher/codegen.yaml deleted file mode 100644 index abead314..00000000 --- a/packages/eden-watcher/codegen.yaml +++ /dev/null @@ -1,43 +0,0 @@ -# Config to generate eden-watcher using codegen. -# Contracts to watch (required). -contracts: - # Contract name. - - name: EdenNetwork - # Contract file path or an url. - path: ~/eden/governance/contracts/EdenNetwork.sol - # Contract kind (should match that in {subgraphPath}/subgraph.yaml if subgraphPath provided) - kind: EdenNetwork - - # Contract name. - - name: MerkleDistributor - # Contract file path or an url. - path: ~/eden/governance/contracts/MerkleDistributor.sol - # Contract kind (should match that in {subgraphPath}/subgraph.yaml if subgraphPath provided) - kind: EdenNetworkDistribution - - # Contract name. - - name: DistributorGovernance - # Contract file path or an url. - path: ~/eden/governance/contracts/DistributorGovernance.sol - # Contract kind (should match that in {subgraphPath}/subgraph.yaml if subgraphPath provided) - kind: EdenNetworkGovernance - -# Output folder path (logs output using `stdout` if not provided). -outputFolder: ../demo-eden-watcher - -# Code generation mode [eth_call | storage | all | none] (default: all). -mode: none - -# Kind of watcher [lazy | active] (default: active). -kind: active - -# Watcher server port (default: 3008). -port: 3012 - -# Flatten the input contract file(s) [true | false] (default: true). -flatten: true - -# Path to the subgraph build (optional). -subgraphPath: ~/eden/eden-data/packages/subgraph/build - -# NOTE: When passed an *URL* as contract path, it is assumed that it points to an already flattened contract file. diff --git a/packages/eden-watcher/environments/local.toml b/packages/eden-watcher/environments/local.toml deleted file mode 100644 index e16fc026..00000000 --- a/packages/eden-watcher/environments/local.toml +++ /dev/null @@ -1,75 +0,0 @@ -[server] - host = "127.0.0.1" - port = 3012 - kind = "active" - - # Checkpointing state. - checkpointing = true - - # Checkpoint interval in number of blocks. - checkpointInterval = 2000 - - subgraphPath = "../graph-node/test/subgraph/eden" - - # Enable state creation - # CAUTION: Disable only if state creation is not desired or can be filled subsequently - enableState = true - - # Interval to restart wasm instance periodically - wasmRestartBlocksInterval = 20 - - # Boolean to filter logs by contract. - filterLogs = true - - # Max block range for which to return events in eventsInRange GQL query. - # Use -1 for skipping check on block range. - maxEventsBlockRange = 1000 - - # Interval in number of blocks at which to clear entities cache. - clearEntitiesCacheInterval = 1000 - - # GQL cache settings - [server.gqlCache] - enabled = true - - # Max in-memory cache size (in bytes) (default 8 MB) - # maxCacheSize - - # GQL cache-control max-age settings (in seconds) - maxAge = 15 - timeTravelMaxAge = 86400 # 1 day - -[metrics] - host = "127.0.0.1" - port = 9000 - [metrics.gql] - port = 9001 - -[database] - type = "postgres" - host = "localhost" - port = 5432 - database = "eden-watcher" - username = "postgres" - password = "postgres" - synchronize = true - logging = false - -[upstream] - [upstream.ethServer] - gqlApiEndpoint = "http://127.0.0.1:8083/graphql" - rpcProviderEndpoint = "http://127.0.0.1:8082" - - [upstream.cache] - name = "requests" - enabled = false - deleteOnStart = false - -[jobQueue] - dbConnectionString = "postgres://postgres:postgres@localhost/eden-watcher-job-queue" - maxCompletionLagInSecs = 300 - jobDelayInMilliSecs = 100 - eventsInBatch = 50 - blockDelayInMilliSecs = 2000 - prefetchBlocksInMem = true - prefetchBlockCount = 10 diff --git a/packages/eden-watcher/package.json b/packages/eden-watcher/package.json deleted file mode 100644 index 285fc24f..00000000 --- a/packages/eden-watcher/package.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "name": "@cerc-io/eden-watcher", - "version": "0.2.38", - "description": "eden-watcher", - "private": true, - "main": "dist/index.js", - "scripts": { - "lint": "eslint .", - "build": "yarn clean && tsc && yarn copy-assets", - "clean": "rm -rf ./dist", - "copy-assets": "copyfiles -u 1 src/**/*.gql dist/", - "server": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true node --enable-source-maps dist/server.js", - "server:dev": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true ts-node src/server.ts", - "job-runner": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true node --max-old-space-size=3072 --enable-source-maps dist/job-runner.js", - "job-runner:dev": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true ts-node src/job-runner.ts", - "watch:contract": "DEBUG=vulcanize:* ts-node src/cli/watch-contract.ts", - "fill": "DEBUG=vulcanize:* ts-node src/fill.ts", - "fill:state": "DEBUG=vulcanize:* ts-node src/fill.ts --state", - "reset": "DEBUG=vulcanize:* ts-node src/cli/reset.ts", - "checkpoint": "DEBUG=vulcanize:* node --enable-source-maps --max-old-space-size=3072 dist/cli/checkpoint.js", - "checkpoint:dev": "DEBUG=vulcanize:* ts-node src/cli/checkpoint.ts", - "export-state": "DEBUG=vulcanize:* node --enable-source-maps --max-old-space-size=3072 dist/cli/export-state.js", - "export-state:dev": "DEBUG=vulcanize:* ts-node src/cli/export-state.ts", - "import-state": "DEBUG=vulcanize:* node --enable-source-maps --max-old-space-size=3072 dist/cli/import-state.js", - "import-state:dev": "DEBUG=vulcanize:* ts-node src/cli/import-state.ts", - "inspect-cid": "DEBUG=vulcanize:* ts-node src/cli/inspect-cid.ts", - "index-block": "DEBUG=vulcanize:* ts-node src/cli/index-block.ts" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/cerc-io/watcher-ts.git" - }, - "author": "", - "license": "AGPL-3.0", - "bugs": { - "url": "https://github.com/cerc-io/watcher-ts/issues" - }, - "homepage": "https://github.com/cerc-io/watcher-ts#readme", - "dependencies": { - "@apollo/client": "^3.3.19", - "@cerc-io/cli": "^0.2.38", - "@cerc-io/graph-node": "^0.2.38", - "@cerc-io/ipld-eth-client": "^0.2.38", - "@cerc-io/solidity-mapper": "^0.2.38", - "@cerc-io/util": "^0.2.38", - "@ethersproject/providers": "^5.4.4", - "apollo-type-bigint": "^0.1.3", - "debug": "^4.3.1", - "decimal.js": "^10.3.1", - "ethers": "^5.4.4", - "graphql": "^15.5.0", - "reflect-metadata": "^0.1.13", - "typeorm": "^0.2.32", - "yargs": "^17.0.1" - }, - "devDependencies": { - "@ethersproject/abi": "^5.3.0", - "@types/yargs": "^17.0.0", - "@typescript-eslint/eslint-plugin": "^5.47.1", - "@typescript-eslint/parser": "^5.47.1", - "copyfiles": "^2.4.1", - "eslint": "^8.35.0", - "eslint-config-semistandard": "^15.0.1", - "eslint-config-standard": "^16.0.3", - "eslint-plugin-import": "^2.27.5", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-promise": "^5.1.0", - "eslint-plugin-standard": "^5.0.0", - "ts-node": "^10.2.1", - "typescript": "^5.0.2" - } -} diff --git a/packages/eden-watcher/src/artifacts/DistributorGovernance.json b/packages/eden-watcher/src/artifacts/DistributorGovernance.json deleted file mode 100644 index f308b6cc..00000000 --- a/packages/eden-watcher/src/artifacts/DistributorGovernance.json +++ /dev/null @@ -1,723 +0,0 @@ -{ - "abi": [ - { - "inputs": [ - { - "internalType": "address", - "name": "_admin", - "type": "address" - }, - { - "internalType": "address[]", - "name": "_blockProducers", - "type": "address[]" - }, - { - "internalType": "address[]", - "name": "_collectors", - "type": "address[]" - } - ], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "producer", - "type": "address" - } - ], - "name": "BlockProducerAdded", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "producer", - "type": "address" - } - ], - "name": "BlockProducerRemoved", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "producer", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "collector", - "type": "address" - } - ], - "name": "BlockProducerRewardCollectorChanged", - "type": "event" - }, - { - "anonymous": false, - "inputs": [], - "name": "RewardScheduleChanged", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "indexed": true, - "internalType": "bytes32", - "name": "previousAdminRole", - "type": "bytes32" - }, - { - "indexed": true, - "internalType": "bytes32", - "name": "newAdminRole", - "type": "bytes32" - } - ], - "name": "RoleAdminChanged", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "indexed": true, - "internalType": "address", - "name": "account", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "sender", - "type": "address" - } - ], - "name": "RoleGranted", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "indexed": true, - "internalType": "address", - "name": "account", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "sender", - "type": "address" - } - ], - "name": "RoleRevoked", - "type": "event" - }, - { - "inputs": [], - "name": "DEFAULT_ADMIN_ROLE", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "DELEGATOR_ROLE", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "GOV_ROLE", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "REWARD_SCHEDULE_ENTRY_LENGTH", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "producer", - "type": "address" - } - ], - "name": "add", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address[]", - "name": "producers", - "type": "address[]" - } - ], - "name": "addBatch", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "name": "blockProducer", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "producer", - "type": "address" - }, - { - "internalType": "address", - "name": "collector", - "type": "address" - } - ], - "name": "delegate", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address[]", - "name": "producers", - "type": "address[]" - }, - { - "internalType": "address[]", - "name": "collectors", - "type": "address[]" - } - ], - "name": "delegateBatch", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - } - ], - "name": "getRoleAdmin", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "internalType": "uint256", - "name": "index", - "type": "uint256" - } - ], - "name": "getRoleMember", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - } - ], - "name": "getRoleMemberCount", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "grantRole", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "hasRole", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "producer", - "type": "address" - } - ], - "name": "remove", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address[]", - "name": "producers", - "type": "address[]" - } - ], - "name": "removeBatch", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "renounceRole", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "revokeRole", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "name": "rewardCollector", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "rewardScheduleEntries", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "index", - "type": "uint256" - } - ], - "name": "rewardScheduleEntry", - "outputs": [ - { - "components": [ - { - "internalType": "uint64", - "name": "startTime", - "type": "uint64" - }, - { - "internalType": "uint64", - "name": "epochDuration", - "type": "uint64" - }, - { - "internalType": "uint128", - "name": "rewardsPerEpoch", - "type": "uint128" - } - ], - "internalType": "struct IGovernance.RewardScheduleEntry", - "name": "", - "type": "tuple" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes", - "name": "set", - "type": "bytes" - } - ], - "name": "setRewardSchedule", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes4", - "name": "interfaceId", - "type": "bytes4" - } - ], - "name": "supportsInterface", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - } - ], - "storageLayout": { - "storage": [ - { - "astId": 380, - "contract": "DistributorGovernance.sol:DistributorGovernance", - "label": "_roles", - "offset": 0, - "slot": "0", - "type": "t_mapping(t_bytes32,t_struct(RoleData)375_storage)" - }, - { - "astId": 1210, - "contract": "DistributorGovernance.sol:DistributorGovernance", - "label": "_roleMembers", - "offset": 0, - "slot": "1", - "type": "t_mapping(t_bytes32,t_struct(AddressSet)969_storage)" - }, - { - "astId": 1721, - "contract": "DistributorGovernance.sol:DistributorGovernance", - "label": "rewardCollector", - "offset": 0, - "slot": "2", - "type": "t_mapping(t_address,t_address)" - }, - { - "astId": 1727, - "contract": "DistributorGovernance.sol:DistributorGovernance", - "label": "blockProducer", - "offset": 0, - "slot": "3", - "type": "t_mapping(t_address,t_bool)" - }, - { - "astId": 1730, - "contract": "DistributorGovernance.sol:DistributorGovernance", - "label": "_rewardSchedule", - "offset": 0, - "slot": "4", - "type": "t_bytes_storage" - } - ], - "types": { - "t_address": { - "encoding": "inplace", - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "base": "t_bytes32", - "encoding": "dynamic_array", - "label": "bytes32[]", - "numberOfBytes": "32" - }, - "t_bool": { - "encoding": "inplace", - "label": "bool", - "numberOfBytes": "1" - }, - "t_bytes32": { - "encoding": "inplace", - "label": "bytes32", - "numberOfBytes": "32" - }, - "t_bytes_storage": { - "encoding": "bytes", - "label": "bytes", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_address)": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => address)", - "numberOfBytes": "32", - "value": "t_address" - }, - "t_mapping(t_address,t_bool)": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => bool)", - "numberOfBytes": "32", - "value": "t_bool" - }, - "t_mapping(t_bytes32,t_struct(AddressSet)969_storage)": { - "encoding": "mapping", - "key": "t_bytes32", - "label": "mapping(bytes32 => struct EnumerableSet.AddressSet)", - "numberOfBytes": "32", - "value": "t_struct(AddressSet)969_storage" - }, - "t_mapping(t_bytes32,t_struct(RoleData)375_storage)": { - "encoding": "mapping", - "key": "t_bytes32", - "label": "mapping(bytes32 => struct AccessControl.RoleData)", - "numberOfBytes": "32", - "value": "t_struct(RoleData)375_storage" - }, - "t_mapping(t_bytes32,t_uint256)": { - "encoding": "mapping", - "key": "t_bytes32", - "label": "mapping(bytes32 => uint256)", - "numberOfBytes": "32", - "value": "t_uint256" - }, - "t_struct(AddressSet)969_storage": { - "encoding": "inplace", - "label": "struct EnumerableSet.AddressSet", - "members": [ - { - "astId": 968, - "contract": "DistributorGovernance.sol:DistributorGovernance", - "label": "_inner", - "offset": 0, - "slot": "0", - "type": "t_struct(Set)698_storage" - } - ], - "numberOfBytes": "64" - }, - "t_struct(RoleData)375_storage": { - "encoding": "inplace", - "label": "struct AccessControl.RoleData", - "members": [ - { - "astId": 372, - "contract": "DistributorGovernance.sol:DistributorGovernance", - "label": "members", - "offset": 0, - "slot": "0", - "type": "t_mapping(t_address,t_bool)" - }, - { - "astId": 374, - "contract": "DistributorGovernance.sol:DistributorGovernance", - "label": "adminRole", - "offset": 0, - "slot": "1", - "type": "t_bytes32" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Set)698_storage": { - "encoding": "inplace", - "label": "struct EnumerableSet.Set", - "members": [ - { - "astId": 693, - "contract": "DistributorGovernance.sol:DistributorGovernance", - "label": "_values", - "offset": 0, - "slot": "0", - "type": "t_array(t_bytes32)dyn_storage" - }, - { - "astId": 697, - "contract": "DistributorGovernance.sol:DistributorGovernance", - "label": "_indexes", - "offset": 0, - "slot": "1", - "type": "t_mapping(t_bytes32,t_uint256)" - } - ], - "numberOfBytes": "64" - }, - "t_uint256": { - "encoding": "inplace", - "label": "uint256", - "numberOfBytes": "32" - } - } - } -} \ No newline at end of file diff --git a/packages/eden-watcher/src/artifacts/EdenNetwork.json b/packages/eden-watcher/src/artifacts/EdenNetwork.json deleted file mode 100644 index 205c9be0..00000000 --- a/packages/eden-watcher/src/artifacts/EdenNetwork.json +++ /dev/null @@ -1,942 +0,0 @@ -{ - "abi": [ - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "newAdmin", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "oldAdmin", - "type": "address" - } - ], - "name": "AdminUpdated", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "uint8", - "name": "slot", - "type": "uint8" - }, - { - "indexed": true, - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint128", - "name": "newBidAmount", - "type": "uint128" - }, - { - "indexed": false, - "internalType": "uint128", - "name": "oldBidAmount", - "type": "uint128" - }, - { - "indexed": false, - "internalType": "uint16", - "name": "taxNumerator", - "type": "uint16" - }, - { - "indexed": false, - "internalType": "uint16", - "name": "taxDenominator", - "type": "uint16" - } - ], - "name": "SlotClaimed", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "uint8", - "name": "slot", - "type": "uint8" - }, - { - "indexed": true, - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "newDelegate", - "type": "address" - }, - { - "indexed": false, - "internalType": "address", - "name": "oldDelegate", - "type": "address" - } - ], - "name": "SlotDelegateUpdated", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "staker", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "stakeAmount", - "type": "uint256" - } - ], - "name": "Stake", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "uint16", - "name": "newNumerator", - "type": "uint16" - }, - { - "indexed": false, - "internalType": "uint16", - "name": "newDenominator", - "type": "uint16" - }, - { - "indexed": false, - "internalType": "uint16", - "name": "oldNumerator", - "type": "uint16" - }, - { - "indexed": false, - "internalType": "uint16", - "name": "oldDenominator", - "type": "uint16" - } - ], - "name": "TaxRateUpdated", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "staker", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "unstakedAmount", - "type": "uint256" - } - ], - "name": "Unstake", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "withdrawer", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "withdrawalAmount", - "type": "uint256" - } - ], - "name": "Withdraw", - "type": "event" - }, - { - "inputs": [], - "name": "MIN_BID", - "outputs": [ - { - "internalType": "uint128", - "name": "", - "type": "uint128" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "admin", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint8", - "name": "slot", - "type": "uint8" - }, - { - "internalType": "uint128", - "name": "bid", - "type": "uint128" - }, - { - "internalType": "address", - "name": "delegate", - "type": "address" - } - ], - "name": "claimSlot", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint8", - "name": "slot", - "type": "uint8" - }, - { - "internalType": "uint128", - "name": "bid", - "type": "uint128" - }, - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "uint256", - "name": "deadline", - "type": "uint256" - }, - { - "internalType": "uint8", - "name": "v", - "type": "uint8" - }, - { - "internalType": "bytes32", - "name": "r", - "type": "bytes32" - }, - { - "internalType": "bytes32", - "name": "s", - "type": "bytes32" - } - ], - "name": "claimSlotWithPermit", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "contract IERC20Extended", - "name": "_token", - "type": "address" - }, - { - "internalType": "contract ILockManager", - "name": "_lockManager", - "type": "address" - }, - { - "internalType": "address", - "name": "_admin", - "type": "address" - }, - { - "internalType": "uint16", - "name": "_taxNumerator", - "type": "uint16" - }, - { - "internalType": "uint16", - "name": "_taxDenominator", - "type": "uint16" - } - ], - "name": "initialize", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "lockManager", - "outputs": [ - { - "internalType": "contract ILockManager", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "name": "lockedBalance", - "outputs": [ - { - "internalType": "uint128", - "name": "", - "type": "uint128" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "newAdmin", - "type": "address" - } - ], - "name": "setAdmin", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint8", - "name": "slot", - "type": "uint8" - }, - { - "internalType": "address", - "name": "delegate", - "type": "address" - } - ], - "name": "setSlotDelegate", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint16", - "name": "numerator", - "type": "uint16" - }, - { - "internalType": "uint16", - "name": "denominator", - "type": "uint16" - } - ], - "name": "setTaxRate", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint8", - "name": "slot", - "type": "uint8" - } - ], - "name": "slotBalance", - "outputs": [ - { - "internalType": "uint128", - "name": "balance", - "type": "uint128" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint8", - "name": "", - "type": "uint8" - } - ], - "name": "slotBid", - "outputs": [ - { - "internalType": "address", - "name": "bidder", - "type": "address" - }, - { - "internalType": "uint16", - "name": "taxNumerator", - "type": "uint16" - }, - { - "internalType": "uint16", - "name": "taxDenominator", - "type": "uint16" - }, - { - "internalType": "uint64", - "name": "periodStart", - "type": "uint64" - }, - { - "internalType": "uint128", - "name": "bidAmount", - "type": "uint128" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint8", - "name": "slot", - "type": "uint8" - } - ], - "name": "slotCost", - "outputs": [ - { - "internalType": "uint128", - "name": "", - "type": "uint128" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint8", - "name": "slot", - "type": "uint8" - } - ], - "name": "slotDelegate", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint8", - "name": "", - "type": "uint8" - } - ], - "name": "slotExpiration", - "outputs": [ - { - "internalType": "uint64", - "name": "", - "type": "uint64" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint8", - "name": "slot", - "type": "uint8" - } - ], - "name": "slotForeclosed", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint8", - "name": "slot", - "type": "uint8" - } - ], - "name": "slotOwner", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint128", - "name": "amount", - "type": "uint128" - } - ], - "name": "stake", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint128", - "name": "amount", - "type": "uint128" - }, - { - "internalType": "uint256", - "name": "deadline", - "type": "uint256" - }, - { - "internalType": "uint8", - "name": "v", - "type": "uint8" - }, - { - "internalType": "bytes32", - "name": "r", - "type": "bytes32" - }, - { - "internalType": "bytes32", - "name": "s", - "type": "bytes32" - } - ], - "name": "stakeWithPermit", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "name": "stakedBalance", - "outputs": [ - { - "internalType": "uint128", - "name": "", - "type": "uint128" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "taxDenominator", - "outputs": [ - { - "internalType": "uint16", - "name": "", - "type": "uint16" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "taxNumerator", - "outputs": [ - { - "internalType": "uint16", - "name": "", - "type": "uint16" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "token", - "outputs": [ - { - "internalType": "contract IERC20Extended", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint128", - "name": "amount", - "type": "uint128" - } - ], - "name": "unstake", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint128", - "name": "amount", - "type": "uint128" - } - ], - "name": "withdraw", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - } - ], - "storageLayout": { - "storage": [ - { - "astId": 322, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "_initialized", - "offset": 0, - "slot": "0", - "type": "t_bool" - }, - { - "astId": 325, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "_initializing", - "offset": 1, - "slot": "0", - "type": "t_bool" - }, - { - "astId": 381, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "slotExpiration", - "offset": 0, - "slot": "1", - "type": "t_mapping(t_uint8,t_uint64)" - }, - { - "astId": 386, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "_slotDelegate", - "offset": 0, - "slot": "2", - "type": "t_mapping(t_uint8,t_address)" - }, - { - "astId": 391, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "_slotOwner", - "offset": 0, - "slot": "3", - "type": "t_mapping(t_uint8,t_address)" - }, - { - "astId": 397, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "slotBid", - "offset": 0, - "slot": "4", - "type": "t_mapping(t_uint8,t_struct(Bid)376_storage)" - }, - { - "astId": 402, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "stakedBalance", - "offset": 0, - "slot": "5", - "type": "t_mapping(t_address,t_uint128)" - }, - { - "astId": 407, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "lockedBalance", - "offset": 0, - "slot": "6", - "type": "t_mapping(t_address,t_uint128)" - }, - { - "astId": 411, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "token", - "offset": 0, - "slot": "7", - "type": "t_contract(IERC20Extended)318" - }, - { - "astId": 415, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "lockManager", - "offset": 0, - "slot": "8", - "type": "t_contract(ILockManager)133" - }, - { - "astId": 418, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "admin", - "offset": 0, - "slot": "9", - "type": "t_address" - }, - { - "astId": 421, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "taxNumerator", - "offset": 20, - "slot": "9", - "type": "t_uint16" - }, - { - "astId": 424, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "taxDenominator", - "offset": 22, - "slot": "9", - "type": "t_uint16" - }, - { - "astId": 427, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "MIN_BID", - "offset": 0, - "slot": "10", - "type": "t_uint128" - }, - { - "astId": 430, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "_NOT_ENTERED", - "offset": 0, - "slot": "11", - "type": "t_uint256" - }, - { - "astId": 433, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "_ENTERED", - "offset": 0, - "slot": "12", - "type": "t_uint256" - }, - { - "astId": 436, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "_status", - "offset": 0, - "slot": "13", - "type": "t_uint256" - } - ], - "types": { - "t_address": { - "encoding": "inplace", - "label": "address", - "numberOfBytes": "20" - }, - "t_bool": { - "encoding": "inplace", - "label": "bool", - "numberOfBytes": "1" - }, - "t_contract(IERC20Extended)318": { - "encoding": "inplace", - "label": "contract IERC20Extended", - "numberOfBytes": "20" - }, - "t_contract(ILockManager)133": { - "encoding": "inplace", - "label": "contract ILockManager", - "numberOfBytes": "20" - }, - "t_mapping(t_address,t_uint128)": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => uint128)", - "numberOfBytes": "32", - "value": "t_uint128" - }, - "t_mapping(t_uint8,t_address)": { - "encoding": "mapping", - "key": "t_uint8", - "label": "mapping(uint8 => address)", - "numberOfBytes": "32", - "value": "t_address" - }, - "t_mapping(t_uint8,t_struct(Bid)376_storage)": { - "encoding": "mapping", - "key": "t_uint8", - "label": "mapping(uint8 => struct EdenNetwork.Bid)", - "numberOfBytes": "32", - "value": "t_struct(Bid)376_storage" - }, - "t_mapping(t_uint8,t_uint64)": { - "encoding": "mapping", - "key": "t_uint8", - "label": "mapping(uint8 => uint64)", - "numberOfBytes": "32", - "value": "t_uint64" - }, - "t_struct(Bid)376_storage": { - "encoding": "inplace", - "label": "struct EdenNetwork.Bid", - "members": [ - { - "astId": 367, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "bidder", - "offset": 0, - "slot": "0", - "type": "t_address" - }, - { - "astId": 369, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "taxNumerator", - "offset": 20, - "slot": "0", - "type": "t_uint16" - }, - { - "astId": 371, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "taxDenominator", - "offset": 22, - "slot": "0", - "type": "t_uint16" - }, - { - "astId": 373, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "periodStart", - "offset": 24, - "slot": "0", - "type": "t_uint64" - }, - { - "astId": 375, - "contract": "EdenNetwork.sol:EdenNetwork", - "label": "bidAmount", - "offset": 0, - "slot": "1", - "type": "t_uint128" - } - ], - "numberOfBytes": "64" - }, - "t_uint128": { - "encoding": "inplace", - "label": "uint128", - "numberOfBytes": "16" - }, - "t_uint16": { - "encoding": "inplace", - "label": "uint16", - "numberOfBytes": "2" - }, - "t_uint256": { - "encoding": "inplace", - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint64": { - "encoding": "inplace", - "label": "uint64", - "numberOfBytes": "8" - }, - "t_uint8": { - "encoding": "inplace", - "label": "uint8", - "numberOfBytes": "1" - } - } - } -} \ No newline at end of file diff --git a/packages/eden-watcher/src/artifacts/MerkleDistributor.json b/packages/eden-watcher/src/artifacts/MerkleDistributor.json deleted file mode 100644 index 04ae9a3c..00000000 --- a/packages/eden-watcher/src/artifacts/MerkleDistributor.json +++ /dev/null @@ -1,1482 +0,0 @@ -{ - "abi": [ - { - "inputs": [ - { - "internalType": "contract IERC20Mintable", - "name": "_token", - "type": "address" - }, - { - "internalType": "address", - "name": "_governance", - "type": "address" - }, - { - "internalType": "address", - "name": "_admin", - "type": "address" - }, - { - "internalType": "uint8", - "name": "_updateThreshold", - "type": "uint8" - }, - { - "internalType": "address[]", - "name": "_updaters", - "type": "address[]" - }, - { - "internalType": "address[]", - "name": "_slashers", - "type": "address[]" - } - ], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "account", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "totalClaimed", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "totalSlashed", - "type": "uint256" - } - ], - "name": "AccountUpdated", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "approved", - "type": "address" - }, - { - "indexed": true, - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - } - ], - "name": "Approval", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "operator", - "type": "address" - }, - { - "indexed": false, - "internalType": "bool", - "name": "approved", - "type": "bool" - } - ], - "name": "ApprovalForAll", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "uint256", - "name": "index", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "totalEarned", - "type": "uint256" - }, - { - "indexed": true, - "internalType": "address", - "name": "account", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "claimed", - "type": "uint256" - } - ], - "name": "Claimed", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "address", - "name": "from", - "type": "address" - }, - { - "indexed": false, - "internalType": "address", - "name": "to", - "type": "address" - } - ], - "name": "GovernanceChanged", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "bytes32", - "name": "merkleRoot", - "type": "bytes32" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "distributionNumber", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "string", - "name": "metadataURI", - "type": "string" - } - ], - "name": "MerkleRootUpdated", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "string", - "name": "value", - "type": "string" - }, - { - "indexed": true, - "internalType": "uint256", - "name": "id", - "type": "uint256" - } - ], - "name": "PermanentURI", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "indexed": true, - "internalType": "bytes32", - "name": "previousAdminRole", - "type": "bytes32" - }, - { - "indexed": true, - "internalType": "bytes32", - "name": "newAdminRole", - "type": "bytes32" - } - ], - "name": "RoleAdminChanged", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "indexed": true, - "internalType": "address", - "name": "account", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "sender", - "type": "address" - } - ], - "name": "RoleGranted", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "indexed": true, - "internalType": "address", - "name": "account", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "sender", - "type": "address" - } - ], - "name": "RoleRevoked", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "account", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "slashed", - "type": "uint256" - } - ], - "name": "Slashed", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "from", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "indexed": true, - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - } - ], - "name": "Transfer", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "uint256", - "name": "updateThreshold", - "type": "uint256" - } - ], - "name": "UpdateThresholdChanged", - "type": "event" - }, - { - "inputs": [], - "name": "DEFAULT_ADMIN_ROLE", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "DISTRIBUTOR_ROLE", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "SLASHER_ROLE", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "UPDATER_ROLE", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "name": "accountState", - "outputs": [ - { - "internalType": "uint256", - "name": "totalClaimed", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "totalSlashed", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address[]", - "name": "newUpdaters", - "type": "address[]" - }, - { - "internalType": "uint256", - "name": "newThreshold", - "type": "uint256" - } - ], - "name": "addUpdaters", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - } - ], - "name": "approve", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "owner", - "type": "address" - } - ], - "name": "balanceOf", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "index", - "type": "uint256" - }, - { - "internalType": "address", - "name": "account", - "type": "address" - }, - { - "internalType": "uint256", - "name": "totalEarned", - "type": "uint256" - }, - { - "internalType": "bytes32[]", - "name": "merkleProof", - "type": "bytes32[]" - } - ], - "name": "claim", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "distributionCount", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - } - ], - "name": "getApproved", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - } - ], - "name": "getRoleAdmin", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "internalType": "uint256", - "name": "index", - "type": "uint256" - } - ], - "name": "getRoleMember", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - } - ], - "name": "getRoleMemberCount", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "governance", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "grantRole", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "hasRole", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "internalType": "address", - "name": "operator", - "type": "address" - } - ], - "name": "isApprovedForAll", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "merkleRoot", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "name", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - } - ], - "name": "ownerOf", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "name": "previousMerkleRoot", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address[]", - "name": "existingUpdaters", - "type": "address[]" - }, - { - "internalType": "uint256", - "name": "newThreshold", - "type": "uint256" - } - ], - "name": "removeUpdaters", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "renounceRole", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "revokeRole", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "from", - "type": "address" - }, - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - } - ], - "name": "safeTransferFrom", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "from", - "type": "address" - }, - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "_data", - "type": "bytes" - } - ], - "name": "safeTransferFrom", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "operator", - "type": "address" - }, - { - "internalType": "bool", - "name": "approved", - "type": "bool" - } - ], - "name": "setApprovalForAll", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "to", - "type": "address" - } - ], - "name": "setGovernance", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "to", - "type": "uint256" - } - ], - "name": "setUpdateThreshold", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "account", - "type": "address" - }, - { - "internalType": "uint256", - "name": "amount", - "type": "uint256" - } - ], - "name": "slash", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes4", - "name": "interfaceId", - "type": "bytes4" - } - ], - "name": "supportsInterface", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "symbol", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "token", - "outputs": [ - { - "internalType": "contract IERC20Mintable", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "index", - "type": "uint256" - } - ], - "name": "tokenByIndex", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "internalType": "uint256", - "name": "index", - "type": "uint256" - } - ], - "name": "tokenOfOwnerByIndex", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - } - ], - "name": "tokenURI", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "totalSupply", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "from", - "type": "address" - }, - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - } - ], - "name": "transferFrom", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "newMerkleRoot", - "type": "bytes32" - }, - { - "internalType": "string", - "name": "uri", - "type": "string" - }, - { - "internalType": "uint256", - "name": "newDistributionNumber", - "type": "uint256" - } - ], - "name": "updateMerkleRoot", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "updateThreshold", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - } - ], - "storageLayout": { - "storage": [ - { - "astId": 2154, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_name", - "offset": 0, - "slot": "0", - "type": "t_string_storage" - }, - { - "astId": 2156, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_symbol", - "offset": 0, - "slot": "1", - "type": "t_string_storage" - }, - { - "astId": 2160, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_owners", - "offset": 0, - "slot": "2", - "type": "t_mapping(t_uint256,t_address)" - }, - { - "astId": 2164, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_balances", - "offset": 0, - "slot": "3", - "type": "t_mapping(t_address,t_uint256)" - }, - { - "astId": 2168, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_tokenApprovals", - "offset": 0, - "slot": "4", - "type": "t_mapping(t_uint256,t_address)" - }, - { - "astId": 2174, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_operatorApprovals", - "offset": 0, - "slot": "5", - "type": "t_mapping(t_address,t_mapping(t_address,t_bool))" - }, - { - "astId": 774, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_roles", - "offset": 0, - "slot": "6", - "type": "t_mapping(t_bytes32,t_struct(RoleData)769_storage)" - }, - { - "astId": 1604, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_roleMembers", - "offset": 0, - "slot": "7", - "type": "t_mapping(t_bytes32,t_struct(AddressSet)1363_storage)" - }, - { - "astId": 2957, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_ownedTokens", - "offset": 0, - "slot": "8", - "type": "t_mapping(t_address,t_mapping(t_uint256,t_uint256))" - }, - { - "astId": 2961, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_ownedTokensIndex", - "offset": 0, - "slot": "9", - "type": "t_mapping(t_uint256,t_uint256)" - }, - { - "astId": 2964, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_allTokens", - "offset": 0, - "slot": "10", - "type": "t_array(t_uint256)dyn_storage" - }, - { - "astId": 2968, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_allTokensIndex", - "offset": 0, - "slot": "11", - "type": "t_mapping(t_uint256,t_uint256)" - }, - { - "astId": 3314, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "merkleRoot", - "offset": 0, - "slot": "12", - "type": "t_bytes32" - }, - { - "astId": 3318, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "distributionCount", - "offset": 0, - "slot": "13", - "type": "t_uint256" - }, - { - "astId": 3321, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "updateThreshold", - "offset": 0, - "slot": "14", - "type": "t_uint256" - }, - { - "astId": 3324, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "governance", - "offset": 0, - "slot": "15", - "type": "t_address" - }, - { - "astId": 3336, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "accountState", - "offset": 0, - "slot": "16", - "type": "t_mapping(t_address,t_struct(AccountState)3329_storage)" - }, - { - "astId": 3342, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "previousMerkleRoot", - "offset": 0, - "slot": "17", - "type": "t_mapping(t_bytes32,t_bool)" - }, - { - "astId": 3347, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_tokenURI", - "offset": 0, - "slot": "18", - "type": "t_mapping(t_uint256,t_string_storage)" - }, - { - "astId": 3352, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_updateVotes", - "offset": 0, - "slot": "19", - "type": "t_mapping(t_bytes32,t_uint256)" - }, - { - "astId": 3359, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_updaterVotes", - "offset": 0, - "slot": "20", - "type": "t_mapping(t_address,t_mapping(t_uint256,t_bytes32))" - } - ], - "types": { - "t_address": { - "encoding": "inplace", - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "base": "t_bytes32", - "encoding": "dynamic_array", - "label": "bytes32[]", - "numberOfBytes": "32" - }, - "t_array(t_uint256)dyn_storage": { - "base": "t_uint256", - "encoding": "dynamic_array", - "label": "uint256[]", - "numberOfBytes": "32" - }, - "t_bool": { - "encoding": "inplace", - "label": "bool", - "numberOfBytes": "1" - }, - "t_bytes32": { - "encoding": "inplace", - "label": "bytes32", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_bool)": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => bool)", - "numberOfBytes": "32", - "value": "t_bool" - }, - "t_mapping(t_address,t_mapping(t_address,t_bool))": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => mapping(address => bool))", - "numberOfBytes": "32", - "value": "t_mapping(t_address,t_bool)" - }, - "t_mapping(t_address,t_mapping(t_uint256,t_bytes32))": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => mapping(uint256 => bytes32))", - "numberOfBytes": "32", - "value": "t_mapping(t_uint256,t_bytes32)" - }, - "t_mapping(t_address,t_mapping(t_uint256,t_uint256))": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => mapping(uint256 => uint256))", - "numberOfBytes": "32", - "value": "t_mapping(t_uint256,t_uint256)" - }, - "t_mapping(t_address,t_struct(AccountState)3329_storage)": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => struct MerkleDistributor.AccountState)", - "numberOfBytes": "32", - "value": "t_struct(AccountState)3329_storage" - }, - "t_mapping(t_address,t_uint256)": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => uint256)", - "numberOfBytes": "32", - "value": "t_uint256" - }, - "t_mapping(t_bytes32,t_bool)": { - "encoding": "mapping", - "key": "t_bytes32", - "label": "mapping(bytes32 => bool)", - "numberOfBytes": "32", - "value": "t_bool" - }, - "t_mapping(t_bytes32,t_struct(AddressSet)1363_storage)": { - "encoding": "mapping", - "key": "t_bytes32", - "label": "mapping(bytes32 => struct EnumerableSet.AddressSet)", - "numberOfBytes": "32", - "value": "t_struct(AddressSet)1363_storage" - }, - "t_mapping(t_bytes32,t_struct(RoleData)769_storage)": { - "encoding": "mapping", - "key": "t_bytes32", - "label": "mapping(bytes32 => struct AccessControl.RoleData)", - "numberOfBytes": "32", - "value": "t_struct(RoleData)769_storage" - }, - "t_mapping(t_bytes32,t_uint256)": { - "encoding": "mapping", - "key": "t_bytes32", - "label": "mapping(bytes32 => uint256)", - "numberOfBytes": "32", - "value": "t_uint256" - }, - "t_mapping(t_uint256,t_address)": { - "encoding": "mapping", - "key": "t_uint256", - "label": "mapping(uint256 => address)", - "numberOfBytes": "32", - "value": "t_address" - }, - "t_mapping(t_uint256,t_bytes32)": { - "encoding": "mapping", - "key": "t_uint256", - "label": "mapping(uint256 => bytes32)", - "numberOfBytes": "32", - "value": "t_bytes32" - }, - "t_mapping(t_uint256,t_string_storage)": { - "encoding": "mapping", - "key": "t_uint256", - "label": "mapping(uint256 => string)", - "numberOfBytes": "32", - "value": "t_string_storage" - }, - "t_mapping(t_uint256,t_uint256)": { - "encoding": "mapping", - "key": "t_uint256", - "label": "mapping(uint256 => uint256)", - "numberOfBytes": "32", - "value": "t_uint256" - }, - "t_string_storage": { - "encoding": "bytes", - "label": "string", - "numberOfBytes": "32" - }, - "t_struct(AccountState)3329_storage": { - "encoding": "inplace", - "label": "struct MerkleDistributor.AccountState", - "members": [ - { - "astId": 3326, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "totalClaimed", - "offset": 0, - "slot": "0", - "type": "t_uint256" - }, - { - "astId": 3328, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "totalSlashed", - "offset": 0, - "slot": "1", - "type": "t_uint256" - } - ], - "numberOfBytes": "64" - }, - "t_struct(AddressSet)1363_storage": { - "encoding": "inplace", - "label": "struct EnumerableSet.AddressSet", - "members": [ - { - "astId": 1362, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_inner", - "offset": 0, - "slot": "0", - "type": "t_struct(Set)1092_storage" - } - ], - "numberOfBytes": "64" - }, - "t_struct(RoleData)769_storage": { - "encoding": "inplace", - "label": "struct AccessControl.RoleData", - "members": [ - { - "astId": 766, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "members", - "offset": 0, - "slot": "0", - "type": "t_mapping(t_address,t_bool)" - }, - { - "astId": 768, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "adminRole", - "offset": 0, - "slot": "1", - "type": "t_bytes32" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Set)1092_storage": { - "encoding": "inplace", - "label": "struct EnumerableSet.Set", - "members": [ - { - "astId": 1087, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_values", - "offset": 0, - "slot": "0", - "type": "t_array(t_bytes32)dyn_storage" - }, - { - "astId": 1091, - "contract": "MerkleDistributor.sol:MerkleDistributor", - "label": "_indexes", - "offset": 0, - "slot": "1", - "type": "t_mapping(t_bytes32,t_uint256)" - } - ], - "numberOfBytes": "64" - }, - "t_uint256": { - "encoding": "inplace", - "label": "uint256", - "numberOfBytes": "32" - } - } - } -} \ No newline at end of file diff --git a/packages/eden-watcher/src/cli/checkpoint-cmds/create.ts b/packages/eden-watcher/src/cli/checkpoint-cmds/create.ts deleted file mode 100644 index e771c702..00000000 --- a/packages/eden-watcher/src/cli/checkpoint-cmds/create.ts +++ /dev/null @@ -1,44 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { CreateCheckpointCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from '../../database'; -import { Indexer } from '../../indexer'; - -export const command = 'create'; - -export const desc = 'Create checkpoint'; - -export const builder = { - address: { - type: 'string', - require: true, - demandOption: true, - describe: 'Contract address to create the checkpoint for.' - }, - blockHash: { - type: 'string', - describe: 'Blockhash at which to create the checkpoint.' - } -}; - -export const handler = async (argv: any): Promise => { - const createCheckpointCmd = new CreateCheckpointCmd(); - await createCheckpointCmd.init(argv, Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - createCheckpointCmd.config.server, - createCheckpointCmd.clients.ethClient, - createCheckpointCmd.ethProvider, - createCheckpointCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await createCheckpointCmd.initIndexer(Indexer, graphWatcher); - - await createCheckpointCmd.exec(); -}; diff --git a/packages/eden-watcher/src/cli/checkpoint-cmds/verify.ts b/packages/eden-watcher/src/cli/checkpoint-cmds/verify.ts deleted file mode 100644 index 3709f543..00000000 --- a/packages/eden-watcher/src/cli/checkpoint-cmds/verify.ts +++ /dev/null @@ -1,40 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { VerifyCheckpointCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from '../../database'; -import { Indexer } from '../../indexer'; - -export const command = 'verify'; - -export const desc = 'Verify checkpoint'; - -export const builder = { - cid: { - type: 'string', - alias: 'c', - demandOption: true, - describe: 'Checkpoint CID to be verified' - } -}; - -export const handler = async (argv: any): Promise => { - const verifyCheckpointCmd = new VerifyCheckpointCmd(); - await verifyCheckpointCmd.init(argv, Database); - - const { graphWatcher, graphDb } = await getGraphDbAndWatcher( - verifyCheckpointCmd.config.server, - verifyCheckpointCmd.clients.ethClient, - verifyCheckpointCmd.ethProvider, - verifyCheckpointCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await verifyCheckpointCmd.initIndexer(Indexer, graphWatcher); - - await verifyCheckpointCmd.exec(graphDb); -}; diff --git a/packages/eden-watcher/src/cli/checkpoint.ts b/packages/eden-watcher/src/cli/checkpoint.ts deleted file mode 100644 index d05ad8ad..00000000 --- a/packages/eden-watcher/src/cli/checkpoint.ts +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import yargs from 'yargs'; -import 'reflect-metadata'; -import debug from 'debug'; - -import { DEFAULT_CONFIG_PATH } from '@cerc-io/util'; - -import { hideBin } from 'yargs/helpers'; - -const log = debug('vulcanize:checkpoint'); - -const main = async () => { - return yargs(hideBin(process.argv)) - .parserConfiguration({ - 'parse-numbers': false - }).options({ - configFile: { - alias: 'f', - type: 'string', - require: true, - demandOption: true, - describe: 'configuration file path (toml)', - default: DEFAULT_CONFIG_PATH - } - }) - .commandDir('checkpoint-cmds', { extensions: ['ts', 'js'], exclude: /([a-zA-Z0-9\s_\\.\-:])+(.d.ts)$/ }) - .demandCommand(1) - .help() - .argv; -}; - -main().then(() => { - process.exit(); -}).catch(err => { - log(err); -}); diff --git a/packages/eden-watcher/src/cli/export-state.ts b/packages/eden-watcher/src/cli/export-state.ts deleted file mode 100644 index bcd1c8ab..00000000 --- a/packages/eden-watcher/src/cli/export-state.ts +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { ExportStateCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:export-state'); - -const main = async (): Promise => { - const exportStateCmd = new ExportStateCmd(); - await exportStateCmd.init(Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - exportStateCmd.config.server, - exportStateCmd.clients.ethClient, - exportStateCmd.ethProvider, - exportStateCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await exportStateCmd.initIndexer(Indexer, graphWatcher); - - await exportStateCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/eden-watcher/src/cli/import-state.ts b/packages/eden-watcher/src/cli/import-state.ts deleted file mode 100644 index 04ce0e8c..00000000 --- a/packages/eden-watcher/src/cli/import-state.ts +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { ImportStateCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from '../database'; -import { Indexer } from '../indexer'; -import { State } from '../entity/State'; - -const log = debug('vulcanize:import-state'); - -export const main = async (): Promise => { - const importStateCmd = new ImportStateCmd(); - await importStateCmd.init(Database); - - const { graphWatcher, graphDb } = await getGraphDbAndWatcher( - importStateCmd.config.server, - importStateCmd.clients.ethClient, - importStateCmd.ethProvider, - importStateCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await importStateCmd.initIndexer(Indexer, graphWatcher); - - await importStateCmd.exec(State, graphDb); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/eden-watcher/src/cli/index-block.ts b/packages/eden-watcher/src/cli/index-block.ts deleted file mode 100644 index 19a302af..00000000 --- a/packages/eden-watcher/src/cli/index-block.ts +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { IndexBlockCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:index-block'); - -const main = async (): Promise => { - const indexBlockCmd = new IndexBlockCmd(); - await indexBlockCmd.init(Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - indexBlockCmd.config.server, - indexBlockCmd.clients.ethClient, - indexBlockCmd.ethProvider, - indexBlockCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await indexBlockCmd.initIndexer(Indexer, graphWatcher); - - await indexBlockCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/eden-watcher/src/cli/inspect-cid.ts b/packages/eden-watcher/src/cli/inspect-cid.ts deleted file mode 100644 index 4f5955ef..00000000 --- a/packages/eden-watcher/src/cli/inspect-cid.ts +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { InspectCIDCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:inspect-cid'); - -const main = async (): Promise => { - const inspectCIDCmd = new InspectCIDCmd(); - await inspectCIDCmd.init(Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - inspectCIDCmd.config.server, - inspectCIDCmd.clients.ethClient, - inspectCIDCmd.ethProvider, - inspectCIDCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await inspectCIDCmd.initIndexer(Indexer, graphWatcher); - - await inspectCIDCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/eden-watcher/src/cli/reset-cmds/job-queue.ts b/packages/eden-watcher/src/cli/reset-cmds/job-queue.ts deleted file mode 100644 index c33cbfd6..00000000 --- a/packages/eden-watcher/src/cli/reset-cmds/job-queue.ts +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import debug from 'debug'; - -import { getConfig, resetJobs, Config } from '@cerc-io/util'; - -const log = debug('vulcanize:reset-job-queue'); - -export const command = 'job-queue'; - -export const desc = 'Reset job queue'; - -export const builder = {}; - -export const handler = async (argv: any): Promise => { - const config: Config = await getConfig(argv.configFile); - await resetJobs(config); - - log('Job queue reset successfully'); -}; diff --git a/packages/eden-watcher/src/cli/reset-cmds/state.ts b/packages/eden-watcher/src/cli/reset-cmds/state.ts deleted file mode 100644 index 33211d6e..00000000 --- a/packages/eden-watcher/src/cli/reset-cmds/state.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { ResetStateCmd } from '@cerc-io/cli'; - -import { Database } from '../../database'; - -export const command = 'state'; - -export const desc = 'Reset State to a given block number'; - -export const builder = { - blockNumber: { - type: 'number' - } -}; - -export const handler = async (argv: any): Promise => { - const resetStateCmd = new ResetStateCmd(); - await resetStateCmd.init(argv, Database); - - await resetStateCmd.exec(); -}; diff --git a/packages/eden-watcher/src/cli/reset-cmds/watcher.ts b/packages/eden-watcher/src/cli/reset-cmds/watcher.ts deleted file mode 100644 index 827fd28d..00000000 --- a/packages/eden-watcher/src/cli/reset-cmds/watcher.ts +++ /dev/null @@ -1,37 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { ResetWatcherCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from '../../database'; -import { Indexer } from '../../indexer'; - -export const command = 'watcher'; - -export const desc = 'Reset watcher to a block number'; - -export const builder = { - blockNumber: { - type: 'number' - } -}; - -export const handler = async (argv: any): Promise => { - const resetWatcherCmd = new ResetWatcherCmd(); - await resetWatcherCmd.init(argv, Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - resetWatcherCmd.config.server, - resetWatcherCmd.clients.ethClient, - resetWatcherCmd.ethProvider, - resetWatcherCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await resetWatcherCmd.initIndexer(Indexer, graphWatcher); - - await resetWatcherCmd.exec(); -}; diff --git a/packages/eden-watcher/src/cli/reset.ts b/packages/eden-watcher/src/cli/reset.ts deleted file mode 100644 index 95648c88..00000000 --- a/packages/eden-watcher/src/cli/reset.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { getResetYargs } from '@cerc-io/util'; - -const log = debug('vulcanize:reset'); - -const main = async () => { - return getResetYargs() - .commandDir('reset-cmds', { extensions: ['ts', 'js'], exclude: /([a-zA-Z0-9\s_\\.\-:])+(.d.ts)$/ }) - .demandCommand(1) - .help() - .argv; -}; - -main().then(() => { - process.exit(); -}).catch(err => { - log(err); -}); diff --git a/packages/eden-watcher/src/cli/watch-contract.ts b/packages/eden-watcher/src/cli/watch-contract.ts deleted file mode 100644 index 7d6ce1a5..00000000 --- a/packages/eden-watcher/src/cli/watch-contract.ts +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { WatchContractCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:watch-contract'); - -const main = async (): Promise => { - const watchContractCmd = new WatchContractCmd(); - await watchContractCmd.init(Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - watchContractCmd.config.server, - watchContractCmd.clients.ethClient, - watchContractCmd.ethProvider, - watchContractCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await watchContractCmd.initIndexer(Indexer, graphWatcher); - - await watchContractCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/eden-watcher/src/client.ts b/packages/eden-watcher/src/client.ts deleted file mode 100644 index 8bb2bb00..00000000 --- a/packages/eden-watcher/src/client.ts +++ /dev/null @@ -1,55 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { gql } from '@apollo/client/core'; -import { GraphQLClient, GraphQLConfig } from '@cerc-io/ipld-eth-client'; - -import { queries, mutations, subscriptions } from './gql'; - -export class Client { - _config: GraphQLConfig; - _client: GraphQLClient; - - constructor (config: GraphQLConfig) { - this._config = config; - - this._client = new GraphQLClient(config); - } - - async getEvents (blockHash: string, contractAddress: string, name: string): Promise { - const { events } = await this._client.query( - gql(queries.events), - { blockHash, contractAddress, name } - ); - - return events; - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise { - const { eventsInRange } = await this._client.query( - gql(queries.eventsInRange), - { fromBlockNumber, toBlockNumber } - ); - - return eventsInRange; - } - - async watchContract (contractAddress: string, startingBlock?: number): Promise { - const { watchContract } = await this._client.mutate( - gql(mutations.watchContract), - { contractAddress, startingBlock } - ); - - return watchContract; - } - - async watchEvents (onNext: (value: any) => void): Promise { - return this._client.subscribe( - gql(subscriptions.onEvent), - ({ data }) => { - onNext(data.onEvent); - } - ); - } -} diff --git a/packages/eden-watcher/src/database.ts b/packages/eden-watcher/src/database.ts deleted file mode 100644 index fdefa693..00000000 --- a/packages/eden-watcher/src/database.ts +++ /dev/null @@ -1,272 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import { Connection, ConnectionOptions, DeepPartial, FindConditions, QueryRunner, FindManyOptions, EntityTarget } from 'typeorm'; -import path from 'path'; - -import { Database as BaseDatabase, DatabaseInterface, QueryOptions, StateKind, Where } from '@cerc-io/util'; - -import { Contract } from './entity/Contract'; -import { Event } from './entity/Event'; -import { SyncStatus } from './entity/SyncStatus'; -import { StateSyncStatus } from './entity/StateSyncStatus'; -import { BlockProgress } from './entity/BlockProgress'; -import { State } from './entity/State'; -import { Account } from './entity/Account'; -import { Claim } from './entity/Claim'; -import { Distribution } from './entity/Distribution'; -import { Distributor } from './entity/Distributor'; -import { Epoch } from './entity/Epoch'; -import { Network } from './entity/Network'; -import { Producer } from './entity/Producer'; -import { ProducerEpoch } from './entity/ProducerEpoch'; -import { ProducerRewardCollectorChange } from './entity/ProducerRewardCollectorChange'; -import { ProducerSet } from './entity/ProducerSet'; -import { ProducerSetChange } from './entity/ProducerSetChange'; -import { RewardSchedule } from './entity/RewardSchedule'; -import { RewardScheduleEntry } from './entity/RewardScheduleEntry'; -import { Slash } from './entity/Slash'; -import { Slot } from './entity/Slot'; -import { SlotClaim } from './entity/SlotClaim'; -import { Staker } from './entity/Staker'; - -export const SUBGRAPH_ENTITIES = new Set([Account, Claim, Distribution, Distributor, Epoch, Network, Producer, ProducerEpoch, ProducerRewardCollectorChange, ProducerSet, ProducerSetChange, RewardSchedule, RewardScheduleEntry, Slash, Slot, SlotClaim, Staker]); -export const ENTITIES = [...SUBGRAPH_ENTITIES]; -export const ENTITY_TO_LATEST_ENTITY_MAP = new Map(); -export const ENTITY_QUERY_TYPE_MAP = new Map(); - -export class Database implements DatabaseInterface { - _config: ConnectionOptions; - _conn!: Connection; - _baseDatabase: BaseDatabase; - - constructor (config: ConnectionOptions) { - assert(config); - - this._config = { - ...config, - entities: [path.join(__dirname, 'entity/*')], - subscribers: [path.join(__dirname, 'entity/Subscriber.*')] - }; - - this._baseDatabase = new BaseDatabase(this._config); - } - - get baseDatabase (): BaseDatabase { - return this._baseDatabase; - } - - async init (): Promise { - this._conn = await this._baseDatabase.init(); - } - - async close (): Promise { - return this._baseDatabase.close(); - } - - getNewState (): State { - return new State(); - } - - async getStates (where: FindConditions): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getStates(repo, where); - } - - async getLatestState (contractAddress: string, kind: StateKind | null, blockNumber?: number): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getLatestState(repo, contractAddress, kind, blockNumber); - } - - async getPrevState (blockHash: string, contractAddress: string, kind?: string): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getPrevState(repo, blockHash, contractAddress, kind); - } - - // Fetch all diff States after the specified block number. - async getDiffStatesInRange (contractAddress: string, startblock: number, endBlock: number): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getDiffStatesInRange(repo, contractAddress, startblock, endBlock); - } - - async saveOrUpdateState (dbTx: QueryRunner, state: State): Promise { - const repo = dbTx.manager.getRepository(State); - - return this._baseDatabase.saveOrUpdateState(repo, state); - } - - async removeStates (dbTx: QueryRunner, blockNumber: number, kind: string): Promise { - const repo = dbTx.manager.getRepository(State); - - await this._baseDatabase.removeStates(repo, blockNumber, kind); - } - - async removeStatesAfterBlock (dbTx: QueryRunner, blockNumber: number): Promise { - const repo = dbTx.manager.getRepository(State); - - await this._baseDatabase.removeStatesAfterBlock(repo, blockNumber); - } - - async getStateSyncStatus (): Promise { - const repo = this._conn.getRepository(StateSyncStatus); - - return this._baseDatabase.getStateSyncStatus(repo); - } - - async updateStateSyncStatusIndexedBlock (queryRunner: QueryRunner, blockNumber: number, force?: boolean): Promise { - const repo = queryRunner.manager.getRepository(StateSyncStatus); - - return this._baseDatabase.updateStateSyncStatusIndexedBlock(repo, blockNumber, force); - } - - async updateStateSyncStatusCheckpointBlock (queryRunner: QueryRunner, blockNumber: number, force?: boolean): Promise { - const repo = queryRunner.manager.getRepository(StateSyncStatus); - - return this._baseDatabase.updateStateSyncStatusCheckpointBlock(repo, blockNumber, force); - } - - async getContracts (): Promise { - const repo = this._conn.getRepository(Contract); - - return this._baseDatabase.getContracts(repo); - } - - async createTransactionRunner (): Promise { - return this._baseDatabase.createTransactionRunner(); - } - - async getProcessedBlockCountForRange (fromBlockNumber: number, toBlockNumber: number): Promise<{ expected: number, actual: number }> { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getProcessedBlockCountForRange(repo, fromBlockNumber, toBlockNumber); - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise> { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getEventsInRange(repo, fromBlockNumber, toBlockNumber); - } - - async saveEventEntity (queryRunner: QueryRunner, entity: Event): Promise { - const repo = queryRunner.manager.getRepository(Event); - return this._baseDatabase.saveEventEntity(repo, entity); - } - - async getBlockEvents (blockHash: string, where: Where, queryOptions: QueryOptions): Promise { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getBlockEvents(repo, blockHash, where, queryOptions); - } - - async saveBlockWithEvents (queryRunner: QueryRunner, block: DeepPartial, events: DeepPartial[]): Promise { - const blockRepo = queryRunner.manager.getRepository(BlockProgress); - const eventRepo = queryRunner.manager.getRepository(Event); - - return this._baseDatabase.saveBlockWithEvents(blockRepo, eventRepo, block, events); - } - - async saveEvents (queryRunner: QueryRunner, events: Event[]): Promise { - const eventRepo = queryRunner.manager.getRepository(Event); - - return this._baseDatabase.saveEvents(eventRepo, events); - } - - async saveBlockProgress (queryRunner: QueryRunner, block: DeepPartial): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.saveBlockProgress(repo, block); - } - - async saveContract (queryRunner: QueryRunner, address: string, kind: string, checkpoint: boolean, startingBlock: number): Promise { - const repo = queryRunner.manager.getRepository(Contract); - - return this._baseDatabase.saveContract(repo, address, kind, checkpoint, startingBlock); - } - - async updateSyncStatusIndexedBlock (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusIndexedBlock(repo, blockHash, blockNumber, force); - } - - async updateSyncStatusCanonicalBlock (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusCanonicalBlock(repo, blockHash, blockNumber, force); - } - - async updateSyncStatusChainHead (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusChainHead(repo, blockHash, blockNumber, force); - } - - async getSyncStatus (queryRunner: QueryRunner): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.getSyncStatus(repo); - } - - async getEvent (id: string): Promise { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getEvent(repo, id); - } - - async getBlocksAtHeight (height: number, isPruned: boolean): Promise { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getBlocksAtHeight(repo, height, isPruned); - } - - async markBlocksAsPruned (queryRunner: QueryRunner, blocks: BlockProgress[]): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.markBlocksAsPruned(repo, blocks); - } - - async getBlockProgress (blockHash: string): Promise { - const repo = this._conn.getRepository(BlockProgress); - return this._baseDatabase.getBlockProgress(repo, blockHash); - } - - async getBlockProgressEntities (where: FindConditions, options: FindManyOptions): Promise { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getBlockProgressEntities(repo, where, options); - } - - async getEntitiesForBlock (blockHash: string, tableName: string): Promise { - return this._baseDatabase.getEntitiesForBlock(blockHash, tableName); - } - - async updateBlockProgress (queryRunner: QueryRunner, block: BlockProgress, lastProcessedEventIndex: number): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.updateBlockProgress(repo, block, lastProcessedEventIndex); - } - - async removeEntities (queryRunner: QueryRunner, entity: new () => Entity, findConditions?: FindManyOptions | FindConditions): Promise { - return this._baseDatabase.removeEntities(queryRunner, entity, findConditions); - } - - async deleteEntitiesByConditions (queryRunner: QueryRunner, entity: EntityTarget, findConditions: FindConditions): Promise { - await this._baseDatabase.deleteEntitiesByConditions(queryRunner, entity, findConditions); - } - - async getAncestorAtDepth (blockHash: string, depth: number): Promise { - return this._baseDatabase.getAncestorAtDepth(blockHash, depth); - } - - _getPropertyColumnMapForEntity (entityName: string): Map { - return this._conn.getMetadata(entityName).ownColumns.reduce((acc, curr) => { - return acc.set(curr.propertyName, curr.databaseName); - }, new Map()); - } -} diff --git a/packages/eden-watcher/src/entity/Account.ts b/packages/eden-watcher/src/entity/Account.ts deleted file mode 100644 index 905c231a..00000000 --- a/packages/eden-watcher/src/entity/Account.ts +++ /dev/null @@ -1,29 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; - -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockNumber']) -export class Account { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('numeric', { transformer: bigintTransformer }) - totalClaimed!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - totalSlashed!: bigint; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/Block.ts b/packages/eden-watcher/src/entity/Block.ts deleted file mode 100644 index 8dab903e..00000000 --- a/packages/eden-watcher/src/entity/Block.ts +++ /dev/null @@ -1,67 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockNumber']) -export class Block { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('boolean') - fromActiveProducer!: boolean; - - @Column('varchar') - hash!: string; - - @Column('varchar') - parentHash!: string; - - @Column('varchar') - unclesHash!: string; - - @Column('varchar') - author!: string; - - @Column('varchar') - stateRoot!: string; - - @Column('varchar') - transactionsRoot!: string; - - @Column('varchar') - receiptsRoot!: string; - - @Column('numeric', { transformer: bigintTransformer }) - number!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - gasUsed!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - gasLimit!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - timestamp!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - difficulty!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - totalDifficulty!: bigint; - - @Column('numeric', { nullable: true, transformer: bigintTransformer }) - size!: bigint; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/BlockProgress.ts b/packages/eden-watcher/src/entity/BlockProgress.ts deleted file mode 100644 index e744aae4..00000000 --- a/packages/eden-watcher/src/entity/BlockProgress.ts +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, CreateDateColumn } from 'typeorm'; -import { BlockProgressInterface } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash'], { unique: true }) -@Index(['blockNumber']) -@Index(['parentHash']) -export class BlockProgress implements BlockProgressInterface { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar') - cid!: string; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('varchar', { length: 66 }) - parentHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('integer') - blockTimestamp!: number; - - @Column('integer') - numEvents!: number; - - @Column('integer') - numProcessedEvents!: number; - - @Column('integer') - lastProcessedEventIndex!: number; - - @Column('boolean') - isComplete!: boolean; - - @Column('boolean', { default: false }) - isPruned!: boolean; - - @CreateDateColumn() - createdAt!: Date; -} diff --git a/packages/eden-watcher/src/entity/Claim.ts b/packages/eden-watcher/src/entity/Claim.ts deleted file mode 100644 index f4ab2d1c..00000000 --- a/packages/eden-watcher/src/entity/Claim.ts +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; - -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockNumber']) -export class Claim { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('numeric', { transformer: bigintTransformer }) - timestamp!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - index!: bigint; - - @Column('varchar') - account!: string; - - @Column('numeric', { transformer: bigintTransformer }) - totalEarned!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - claimed!: bigint; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/Contract.ts b/packages/eden-watcher/src/entity/Contract.ts deleted file mode 100644 index de66b387..00000000 --- a/packages/eden-watcher/src/entity/Contract.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['address'], { unique: true }) -export class Contract { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 42 }) - address!: string; - - @Column('varchar') - kind!: string; - - @Column('boolean') - checkpoint!: boolean; - - @Column('integer') - startingBlock!: number; -} diff --git a/packages/eden-watcher/src/entity/Distribution.ts b/packages/eden-watcher/src/entity/Distribution.ts deleted file mode 100644 index 181f8cf4..00000000 --- a/packages/eden-watcher/src/entity/Distribution.ts +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; - -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockNumber']) -export class Distribution { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar') - distributor!: string; - - @Column('numeric', { transformer: bigintTransformer }) - timestamp!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - distributionNumber!: bigint; - - @Column('varchar') - merkleRoot!: string; - - @Column('varchar') - metadataURI!: string; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/Distributor.ts b/packages/eden-watcher/src/entity/Distributor.ts deleted file mode 100644 index a3d90e0d..00000000 --- a/packages/eden-watcher/src/entity/Distributor.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockNumber']) -export class Distributor { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { nullable: true }) - currentDistribution!: string; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/Epoch.ts b/packages/eden-watcher/src/entity/Epoch.ts deleted file mode 100644 index c1430aae..00000000 --- a/packages/eden-watcher/src/entity/Epoch.ts +++ /dev/null @@ -1,45 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; -import Decimal from 'decimal.js'; - -import { bigintTransformer, decimalTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockNumber']) -export class Epoch { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('boolean') - finalized!: boolean; - - @Column('numeric', { transformer: bigintTransformer }) - epochNumber!: bigint; - - @Column('varchar', { nullable: true }) - startBlock!: string; - - @Column('varchar', { nullable: true }) - endBlock!: string; - - @Column('numeric', { transformer: bigintTransformer }) - producerBlocks!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - allBlocks!: bigint; - - @Column('numeric', { default: 0, transformer: decimalTransformer }) - producerBlocksRatio!: Decimal; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/Event.ts b/packages/eden-watcher/src/entity/Event.ts deleted file mode 100644 index 91f1e6d3..00000000 --- a/packages/eden-watcher/src/entity/Event.ts +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, ManyToOne } from 'typeorm'; -import { BlockProgress } from './BlockProgress'; - -@Entity() -@Index(['block', 'contract']) -@Index(['block', 'contract', 'eventName']) -export class Event { - @PrimaryGeneratedColumn() - id!: number; - - @ManyToOne(() => BlockProgress, { onDelete: 'CASCADE' }) - block!: BlockProgress; - - @Column('varchar', { length: 66 }) - txHash!: string; - - @Column('integer') - index!: number; - - @Column('varchar', { length: 42 }) - contract!: string; - - @Column('varchar', { length: 256 }) - eventName!: string; - - @Column('text') - eventInfo!: string; - - @Column('text') - extraInfo!: string; - - @Column('text') - proof!: string; -} diff --git a/packages/eden-watcher/src/entity/FrothyEntity.ts b/packages/eden-watcher/src/entity/FrothyEntity.ts deleted file mode 100644 index dbbbab7b..00000000 --- a/packages/eden-watcher/src/entity/FrothyEntity.ts +++ /dev/null @@ -1,21 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockNumber']) -export class FrothyEntity { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar') - name!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; -} diff --git a/packages/eden-watcher/src/entity/Network.ts b/packages/eden-watcher/src/entity/Network.ts deleted file mode 100644 index 8dc13eee..00000000 --- a/packages/eden-watcher/src/entity/Network.ts +++ /dev/null @@ -1,45 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; - -import { bigintArrayTransformer, bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockNumber']) -export class Network { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { nullable: true }) - slot0!: string; - - @Column('varchar', { nullable: true }) - slot1!: string; - - @Column('varchar', { nullable: true }) - slot2!: string; - - @Column('varchar', { array: true }) - stakers!: string[]; - - @Column('numeric', { nullable: true, transformer: bigintTransformer }) - numStakers!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - totalStaked!: bigint; - - // https://github.com/brianc/node-postgres/issues/1943#issuecomment-520500053 - @Column('varchar', { transformer: bigintArrayTransformer, array: true }) - stakedPercentiles!: bigint[]; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/Producer.ts b/packages/eden-watcher/src/entity/Producer.ts deleted file mode 100644 index 6d450da5..00000000 --- a/packages/eden-watcher/src/entity/Producer.ts +++ /dev/null @@ -1,37 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockNumber']) -export class Producer { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('boolean') - active!: boolean; - - @Column('varchar', { nullable: true }) - rewardCollector!: string; - - @Column('numeric', { transformer: bigintTransformer }) - rewards!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - confirmedBlocks!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - pendingEpochBlocks!: bigint; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/ProducerEpoch.ts b/packages/eden-watcher/src/entity/ProducerEpoch.ts deleted file mode 100644 index c250a436..00000000 --- a/packages/eden-watcher/src/entity/ProducerEpoch.ts +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; -import Decimal from 'decimal.js'; - -import { bigintTransformer, decimalTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockNumber']) -export class ProducerEpoch { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar') - address!: string; - - @Column('varchar') - epoch!: string; - - @Column('numeric', { transformer: bigintTransformer }) - totalRewards!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - blocksProduced!: bigint; - - @Column('numeric', { default: 0, transformer: decimalTransformer }) - blocksProducedRatio!: Decimal; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/ProducerRewardCollectorChange.ts b/packages/eden-watcher/src/entity/ProducerRewardCollectorChange.ts deleted file mode 100644 index ac529ab2..00000000 --- a/packages/eden-watcher/src/entity/ProducerRewardCollectorChange.ts +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockNumber']) -export class ProducerRewardCollectorChange { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('numeric', { transformer: bigintTransformer }) - _blockNumber!: bigint; - - @Column('varchar') - producer!: string; - - @Column('varchar') - rewardCollector!: string; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/ProducerSet.ts b/packages/eden-watcher/src/entity/ProducerSet.ts deleted file mode 100644 index 3a0f3f23..00000000 --- a/packages/eden-watcher/src/entity/ProducerSet.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockNumber']) -export class ProducerSet { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { array: true }) - producers!: string[]; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/ProducerSetChange.ts b/packages/eden-watcher/src/entity/ProducerSetChange.ts deleted file mode 100644 index 28ac3dd8..00000000 --- a/packages/eden-watcher/src/entity/ProducerSetChange.ts +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -enum ProducerSetChangeType { - Added = 'Added', - Removed = 'Removed' -} - -@Entity() -@Index(['blockNumber']) -export class ProducerSetChange { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('numeric', { transformer: bigintTransformer }) - _blockNumber!: bigint; - - @Column('varchar') - producer!: string; - - @Column({ - type: 'enum', - enum: ProducerSetChangeType - }) - changeType!: ProducerSetChangeType; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/RewardSchedule.ts b/packages/eden-watcher/src/entity/RewardSchedule.ts deleted file mode 100644 index bc21c6f4..00000000 --- a/packages/eden-watcher/src/entity/RewardSchedule.ts +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockNumber']) -export class RewardSchedule { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { array: true }) - rewardScheduleEntries!: string[]; - - @Column('varchar', { nullable: true }) - lastEpoch!: string; - - @Column('varchar', { nullable: true }) - pendingEpoch!: string; - - @Column('varchar', { nullable: true }) - activeRewardScheduleEntry!: string; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/RewardScheduleEntry.ts b/packages/eden-watcher/src/entity/RewardScheduleEntry.ts deleted file mode 100644 index b7cf9cbb..00000000 --- a/packages/eden-watcher/src/entity/RewardScheduleEntry.ts +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockNumber']) -export class RewardScheduleEntry { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('numeric', { transformer: bigintTransformer }) - startTime!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - epochDuration!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - rewardsPerEpoch!: bigint; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/Slash.ts b/packages/eden-watcher/src/entity/Slash.ts deleted file mode 100644 index 42fe57ac..00000000 --- a/packages/eden-watcher/src/entity/Slash.ts +++ /dev/null @@ -1,32 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; - -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockNumber']) -export class Slash { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('numeric', { transformer: bigintTransformer }) - timestamp!: bigint; - - @Column('varchar') - account!: string; - - @Column('numeric', { transformer: bigintTransformer }) - slashed!: bigint; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/Slot.ts b/packages/eden-watcher/src/entity/Slot.ts deleted file mode 100644 index 1cb1473d..00000000 --- a/packages/eden-watcher/src/entity/Slot.ts +++ /dev/null @@ -1,45 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; -import Decimal from 'decimal.js'; - -import { bigintTransformer, decimalTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockNumber']) -export class Slot { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar') - owner!: string; - - @Column('varchar') - delegate!: string; - - @Column('numeric', { transformer: bigintTransformer }) - winningBid!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - oldBid!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - startTime!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - expirationTime!: bigint; - - @Column('numeric', { default: 0, transformer: decimalTransformer }) - taxRatePerDay!: Decimal; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/SlotClaim.ts b/packages/eden-watcher/src/entity/SlotClaim.ts deleted file mode 100644 index 4f4f8fe8..00000000 --- a/packages/eden-watcher/src/entity/SlotClaim.ts +++ /dev/null @@ -1,45 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; -import Decimal from 'decimal.js'; - -import { bigintTransformer, decimalTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockNumber']) -export class SlotClaim { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar') - slot!: string; - - @Column('varchar') - owner!: string; - - @Column('numeric', { transformer: bigintTransformer }) - winningBid!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - oldBid!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - startTime!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - expirationTime!: bigint; - - @Column('numeric', { default: 0, transformer: decimalTransformer }) - taxRatePerDay!: Decimal; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/Staker.ts b/packages/eden-watcher/src/entity/Staker.ts deleted file mode 100644 index d8f5ca82..00000000 --- a/packages/eden-watcher/src/entity/Staker.ts +++ /dev/null @@ -1,28 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockNumber']) -export class Staker { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('numeric', { transformer: bigintTransformer }) - staked!: bigint; - - @Column('numeric', { nullable: true, transformer: bigintTransformer }) - rank!: bigint; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/eden-watcher/src/entity/State.ts b/packages/eden-watcher/src/entity/State.ts deleted file mode 100644 index 10ef261e..00000000 --- a/packages/eden-watcher/src/entity/State.ts +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, ManyToOne } from 'typeorm'; - -import { StateKind } from '@cerc-io/util'; - -import { BlockProgress } from './BlockProgress'; - -@Entity() -@Index(['cid'], { unique: true }) -@Index(['block', 'contractAddress']) -@Index(['block', 'contractAddress', 'kind'], { unique: true }) -export class State { - @PrimaryGeneratedColumn() - id!: number; - - @ManyToOne(() => BlockProgress, { onDelete: 'CASCADE' }) - block!: BlockProgress; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - cid!: string; - - @Column({ - type: 'enum', - enum: StateKind - }) - kind!: StateKind; - - @Column('bytea') - data!: Buffer; -} diff --git a/packages/eden-watcher/src/entity/StateSyncStatus.ts b/packages/eden-watcher/src/entity/StateSyncStatus.ts deleted file mode 100644 index c795212f..00000000 --- a/packages/eden-watcher/src/entity/StateSyncStatus.ts +++ /dev/null @@ -1,17 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; - -@Entity() -export class StateSyncStatus { - @PrimaryGeneratedColumn() - id!: number; - - @Column('integer') - latestIndexedBlockNumber!: number; - - @Column('integer', { nullable: true }) - latestCheckpointBlockNumber!: number; -} diff --git a/packages/eden-watcher/src/entity/Subscriber.ts b/packages/eden-watcher/src/entity/Subscriber.ts deleted file mode 100644 index 2cccb841..00000000 --- a/packages/eden-watcher/src/entity/Subscriber.ts +++ /dev/null @@ -1,21 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { EventSubscriber, EntitySubscriberInterface, InsertEvent, UpdateEvent } from 'typeorm'; - -import { afterEntityInsertOrUpdate } from '@cerc-io/util'; - -import { FrothyEntity } from './FrothyEntity'; -import { ENTITY_TO_LATEST_ENTITY_MAP, SUBGRAPH_ENTITIES } from '../database'; - -@EventSubscriber() -export class EntitySubscriber implements EntitySubscriberInterface { - async afterInsert (event: InsertEvent): Promise { - await afterEntityInsertOrUpdate(FrothyEntity, SUBGRAPH_ENTITIES, event, ENTITY_TO_LATEST_ENTITY_MAP); - } - - async afterUpdate (event: UpdateEvent): Promise { - await afterEntityInsertOrUpdate(FrothyEntity, SUBGRAPH_ENTITIES, event, ENTITY_TO_LATEST_ENTITY_MAP); - } -} diff --git a/packages/eden-watcher/src/entity/SyncStatus.ts b/packages/eden-watcher/src/entity/SyncStatus.ts deleted file mode 100644 index 19d0dfa7..00000000 --- a/packages/eden-watcher/src/entity/SyncStatus.ts +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; -import { SyncStatusInterface } from '@cerc-io/util'; - -@Entity() -export class SyncStatus implements SyncStatusInterface { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - chainHeadBlockHash!: string; - - @Column('integer') - chainHeadBlockNumber!: number; - - @Column('varchar', { length: 66 }) - latestIndexedBlockHash!: string; - - @Column('integer') - latestIndexedBlockNumber!: number; - - @Column('varchar', { length: 66 }) - latestCanonicalBlockHash!: string; - - @Column('integer') - latestCanonicalBlockNumber!: number; - - @Column('varchar', { length: 66 }) - initialIndexedBlockHash!: string; - - @Column('integer') - initialIndexedBlockNumber!: number; -} diff --git a/packages/eden-watcher/src/fill.ts b/packages/eden-watcher/src/fill.ts deleted file mode 100644 index a8906f85..00000000 --- a/packages/eden-watcher/src/fill.ts +++ /dev/null @@ -1,44 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { FillCmd } from '@cerc-io/cli'; -import { getContractEntitiesMap } from '@cerc-io/util'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from './database'; -import { Indexer } from './indexer'; - -const log = debug('vulcanize:fill'); - -export const main = async (): Promise => { - const fillCmd = new FillCmd(); - await fillCmd.init(Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - fillCmd.config.server, - fillCmd.clients.ethClient, - fillCmd.ethProvider, - fillCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await fillCmd.initIndexer(Indexer, graphWatcher); - - // Get contractEntitiesMap required for fill-state - // NOTE: Assuming each entity type is only mapped to a single contract - // This is true for eden subgraph; may not be the case for other subgraphs - const contractEntitiesMap = getContractEntitiesMap(graphWatcher.dataSources); - - await fillCmd.exec(contractEntitiesMap); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(); -}); diff --git a/packages/eden-watcher/src/gql/index.ts b/packages/eden-watcher/src/gql/index.ts deleted file mode 100644 index 4732f682..00000000 --- a/packages/eden-watcher/src/gql/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * as mutations from './mutations'; -export * as queries from './queries'; -export * as subscriptions from './subscriptions'; diff --git a/packages/eden-watcher/src/gql/mutations/index.ts b/packages/eden-watcher/src/gql/mutations/index.ts deleted file mode 100644 index 0c3bd853..00000000 --- a/packages/eden-watcher/src/gql/mutations/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -import fs from 'fs'; -import path from 'path'; - -export const watchContract = fs.readFileSync(path.join(__dirname, 'watchContract.gql'), 'utf8'); diff --git a/packages/eden-watcher/src/gql/mutations/watchContract.gql b/packages/eden-watcher/src/gql/mutations/watchContract.gql deleted file mode 100644 index ef65c717..00000000 --- a/packages/eden-watcher/src/gql/mutations/watchContract.gql +++ /dev/null @@ -1,3 +0,0 @@ -mutation watchContract($address: String!, $kind: String!, $checkpoint: Boolean!, $startingBlock: Int){ - watchContract(address: $address, kind: $kind, checkpoint: $checkpoint, startingBlock: $startingBlock) -} diff --git a/packages/eden-watcher/src/gql/queries/account.gql b/packages/eden-watcher/src/gql/queries/account.gql deleted file mode 100644 index c07f1a39..00000000 --- a/packages/eden-watcher/src/gql/queries/account.gql +++ /dev/null @@ -1,19 +0,0 @@ -query account($id: String!, $block: Block_height){ - account(id: $id, block: $block){ - id - totalClaimed - totalSlashed - claims{ - id - timestamp - index - totalEarned - claimed - } - slashes{ - id - timestamp - slashed - } - } -} diff --git a/packages/eden-watcher/src/gql/queries/block.gql b/packages/eden-watcher/src/gql/queries/block.gql deleted file mode 100644 index ab1c9ae4..00000000 --- a/packages/eden-watcher/src/gql/queries/block.gql +++ /dev/null @@ -1,20 +0,0 @@ -query block($id: String!, $block: Block_height){ - block(id: $id, block: $block){ - id - fromActiveProducer - hash - parentHash - unclesHash - author - stateRoot - transactionsRoot - receiptsRoot - number - gasUsed - gasLimit - timestamp - difficulty - totalDifficulty - size - } -} diff --git a/packages/eden-watcher/src/gql/queries/claim.gql b/packages/eden-watcher/src/gql/queries/claim.gql deleted file mode 100644 index 4b79c418..00000000 --- a/packages/eden-watcher/src/gql/queries/claim.gql +++ /dev/null @@ -1,14 +0,0 @@ -query claim($id: String!, $block: Block_height){ - claim(id: $id, block: $block){ - id - timestamp - index - account{ - id - totalClaimed - totalSlashed - } - totalEarned - claimed - } -} diff --git a/packages/eden-watcher/src/gql/queries/distribution.gql b/packages/eden-watcher/src/gql/queries/distribution.gql deleted file mode 100644 index b838cca2..00000000 --- a/packages/eden-watcher/src/gql/queries/distribution.gql +++ /dev/null @@ -1,12 +0,0 @@ -query distribution($id: String!, $block: Block_height){ - distribution(id: $id, block: $block){ - id - distributor{ - id - } - timestamp - distributionNumber - merkleRoot - metadataURI - } -} diff --git a/packages/eden-watcher/src/gql/queries/distributor.gql b/packages/eden-watcher/src/gql/queries/distributor.gql deleted file mode 100644 index 575703f4..00000000 --- a/packages/eden-watcher/src/gql/queries/distributor.gql +++ /dev/null @@ -1,12 +0,0 @@ -query distributor($id: String!, $block: Block_height){ - distributor(id: $id, block: $block){ - id - currentDistribution{ - id - timestamp - distributionNumber - merkleRoot - metadataURI - } - } -} diff --git a/packages/eden-watcher/src/gql/queries/epoch.gql b/packages/eden-watcher/src/gql/queries/epoch.gql deleted file mode 100644 index 5d878965..00000000 --- a/packages/eden-watcher/src/gql/queries/epoch.gql +++ /dev/null @@ -1,53 +0,0 @@ -query epoch($id: String!, $block: Block_height){ - epoch(id: $id, block: $block){ - id - finalized - epochNumber - startBlock{ - id - fromActiveProducer - hash - parentHash - unclesHash - author - stateRoot - transactionsRoot - receiptsRoot - number - gasUsed - gasLimit - timestamp - difficulty - totalDifficulty - size - } - endBlock{ - id - fromActiveProducer - hash - parentHash - unclesHash - author - stateRoot - transactionsRoot - receiptsRoot - number - gasUsed - gasLimit - timestamp - difficulty - totalDifficulty - size - } - producerBlocks - allBlocks - producerBlocksRatio - producerRewards{ - id - address - totalRewards - blocksProduced - blocksProducedRatio - } - } -} diff --git a/packages/eden-watcher/src/gql/queries/events.gql b/packages/eden-watcher/src/gql/queries/events.gql deleted file mode 100644 index b539cb1b..00000000 --- a/packages/eden-watcher/src/gql/queries/events.gql +++ /dev/null @@ -1,139 +0,0 @@ -query events($blockHash: String!, $contractAddress: String!, $name: String){ - events(blockHash: $blockHash, contractAddress: $contractAddress, name: $name){ - block{ - cid - hash - number - timestamp - parentHash - } - tx{ - hash - index - from - to - } - contract - eventIndex - event{ - ... on TransferEvent { - from - to - value - } - ... on ApprovalEvent { - owner - spender - value - } - ... on AuthorizationUsedEvent { - authorizer - nonce - } - ... on AdminUpdatedEvent { - newAdmin - oldAdmin - } - ... on TaxRateUpdatedEvent { - newNumerator - newDenominator - oldNumerator - oldDenominator - } - ... on SlotClaimedEvent { - slot - owner - delegate - newBidAmount - oldBidAmount - taxNumerator - taxDenominator - } - ... on SlotDelegateUpdatedEvent { - slot - owner - newDelegate - oldDelegate - } - ... on StakeEvent { - staker - stakeAmount - } - ... on UnstakeEvent { - staker - unstakedAmount - } - ... on WithdrawEvent { - withdrawer - withdrawalAmount - } - ... on ApprovalForAllEvent { - owner - operator - approved - } - ... on BlockProducerAddedEvent { - producer - } - ... on BlockProducerRemovedEvent { - producer - } - ... on BlockProducerRewardCollectorChangedEvent { - producer - collector - } - ... on RewardScheduleChangedEvent { - dummy - } - ... on ClaimedEvent { - index - totalEarned - account - claimed - } - ... on SlashedEvent { - account - slashed - } - ... on MerkleRootUpdatedEvent { - merkleRoot - distributionNumber - metadataURI - } - ... on AccountUpdatedEvent { - account - totalClaimed - totalSlashed - } - ... on PermanentURIEvent { - value - id - } - ... on GovernanceChangedEvent { - from - to - } - ... on UpdateThresholdChangedEvent { - updateThreshold - } - ... on RoleAdminChangedEvent { - role - previousAdminRole - newAdminRole - } - ... on RoleGrantedEvent { - role - account - sender - } - ... on RoleRevokedEvent { - role - account - sender - } - } - proof{ - data - } - } -} diff --git a/packages/eden-watcher/src/gql/queries/eventsInRange.gql b/packages/eden-watcher/src/gql/queries/eventsInRange.gql deleted file mode 100644 index 69eec710..00000000 --- a/packages/eden-watcher/src/gql/queries/eventsInRange.gql +++ /dev/null @@ -1,139 +0,0 @@ -query eventsInRange($fromBlockNumber: Int!, $toBlockNumber: Int!){ - eventsInRange(fromBlockNumber: $fromBlockNumber, toBlockNumber: $toBlockNumber){ - block{ - cid - hash - number - timestamp - parentHash - } - tx{ - hash - index - from - to - } - contract - eventIndex - event{ - ... on TransferEvent { - from - to - value - } - ... on ApprovalEvent { - owner - spender - value - } - ... on AuthorizationUsedEvent { - authorizer - nonce - } - ... on AdminUpdatedEvent { - newAdmin - oldAdmin - } - ... on TaxRateUpdatedEvent { - newNumerator - newDenominator - oldNumerator - oldDenominator - } - ... on SlotClaimedEvent { - slot - owner - delegate - newBidAmount - oldBidAmount - taxNumerator - taxDenominator - } - ... on SlotDelegateUpdatedEvent { - slot - owner - newDelegate - oldDelegate - } - ... on StakeEvent { - staker - stakeAmount - } - ... on UnstakeEvent { - staker - unstakedAmount - } - ... on WithdrawEvent { - withdrawer - withdrawalAmount - } - ... on ApprovalForAllEvent { - owner - operator - approved - } - ... on BlockProducerAddedEvent { - producer - } - ... on BlockProducerRemovedEvent { - producer - } - ... on BlockProducerRewardCollectorChangedEvent { - producer - collector - } - ... on RewardScheduleChangedEvent { - dummy - } - ... on ClaimedEvent { - index - totalEarned - account - claimed - } - ... on SlashedEvent { - account - slashed - } - ... on MerkleRootUpdatedEvent { - merkleRoot - distributionNumber - metadataURI - } - ... on AccountUpdatedEvent { - account - totalClaimed - totalSlashed - } - ... on PermanentURIEvent { - value - id - } - ... on GovernanceChangedEvent { - from - to - } - ... on UpdateThresholdChangedEvent { - updateThreshold - } - ... on RoleAdminChangedEvent { - role - previousAdminRole - newAdminRole - } - ... on RoleGrantedEvent { - role - account - sender - } - ... on RoleRevokedEvent { - role - account - sender - } - } - proof{ - data - } - } -} diff --git a/packages/eden-watcher/src/gql/queries/getState.gql b/packages/eden-watcher/src/gql/queries/getState.gql deleted file mode 100644 index 7fded350..00000000 --- a/packages/eden-watcher/src/gql/queries/getState.gql +++ /dev/null @@ -1,15 +0,0 @@ -query getState($blockHash: String!, $contractAddress: String!, $kind: String){ - getState(blockHash: $blockHash, contractAddress: $contractAddress, kind: $kind){ - block{ - cid - hash - number - timestamp - parentHash - } - contractAddress - cid - kind - data - } -} diff --git a/packages/eden-watcher/src/gql/queries/getStateByCID.gql b/packages/eden-watcher/src/gql/queries/getStateByCID.gql deleted file mode 100644 index 8e57fea1..00000000 --- a/packages/eden-watcher/src/gql/queries/getStateByCID.gql +++ /dev/null @@ -1,15 +0,0 @@ -query getStateByCID($cid: String!){ - getStateByCID(cid: $cid){ - block{ - cid - hash - number - timestamp - parentHash - } - contractAddress - cid - kind - data - } -} diff --git a/packages/eden-watcher/src/gql/queries/index.ts b/packages/eden-watcher/src/gql/queries/index.ts deleted file mode 100644 index a57136ed..00000000 --- a/packages/eden-watcher/src/gql/queries/index.ts +++ /dev/null @@ -1,24 +0,0 @@ -import fs from 'fs'; -import path from 'path'; - -export const events = fs.readFileSync(path.join(__dirname, 'events.gql'), 'utf8'); -export const eventsInRange = fs.readFileSync(path.join(__dirname, 'eventsInRange.gql'), 'utf8'); -export const producer = fs.readFileSync(path.join(__dirname, 'producer.gql'), 'utf8'); -export const producerSet = fs.readFileSync(path.join(__dirname, 'producerSet.gql'), 'utf8'); -export const producerSetChange = fs.readFileSync(path.join(__dirname, 'producerSetChange.gql'), 'utf8'); -export const producerRewardCollectorChange = fs.readFileSync(path.join(__dirname, 'producerRewardCollectorChange.gql'), 'utf8'); -export const rewardScheduleEntry = fs.readFileSync(path.join(__dirname, 'rewardScheduleEntry.gql'), 'utf8'); -export const rewardSchedule = fs.readFileSync(path.join(__dirname, 'rewardSchedule.gql'), 'utf8'); -export const producerEpoch = fs.readFileSync(path.join(__dirname, 'producerEpoch.gql'), 'utf8'); -export const epoch = fs.readFileSync(path.join(__dirname, 'epoch.gql'), 'utf8'); -export const slotClaim = fs.readFileSync(path.join(__dirname, 'slotClaim.gql'), 'utf8'); -export const slot = fs.readFileSync(path.join(__dirname, 'slot.gql'), 'utf8'); -export const staker = fs.readFileSync(path.join(__dirname, 'staker.gql'), 'utf8'); -export const network = fs.readFileSync(path.join(__dirname, 'network.gql'), 'utf8'); -export const distributor = fs.readFileSync(path.join(__dirname, 'distributor.gql'), 'utf8'); -export const distribution = fs.readFileSync(path.join(__dirname, 'distribution.gql'), 'utf8'); -export const claim = fs.readFileSync(path.join(__dirname, 'claim.gql'), 'utf8'); -export const slash = fs.readFileSync(path.join(__dirname, 'slash.gql'), 'utf8'); -export const account = fs.readFileSync(path.join(__dirname, 'account.gql'), 'utf8'); -export const getStateByCID = fs.readFileSync(path.join(__dirname, 'getStateByCID.gql'), 'utf8'); -export const getState = fs.readFileSync(path.join(__dirname, 'getState.gql'), 'utf8'); diff --git a/packages/eden-watcher/src/gql/queries/network.gql b/packages/eden-watcher/src/gql/queries/network.gql deleted file mode 100644 index e5daf160..00000000 --- a/packages/eden-watcher/src/gql/queries/network.gql +++ /dev/null @@ -1,43 +0,0 @@ -query network($id: String!, $block: Block_height){ - network(id: $id, block: $block){ - id - slot0{ - id - owner - delegate - winningBid - oldBid - startTime - expirationTime - taxRatePerDay - } - slot1{ - id - owner - delegate - winningBid - oldBid - startTime - expirationTime - taxRatePerDay - } - slot2{ - id - owner - delegate - winningBid - oldBid - startTime - expirationTime - taxRatePerDay - } - stakers{ - id - staked - rank - } - numStakers - totalStaked - stakedPercentiles - } -} diff --git a/packages/eden-watcher/src/gql/queries/producer.gql b/packages/eden-watcher/src/gql/queries/producer.gql deleted file mode 100644 index 47fbe7ee..00000000 --- a/packages/eden-watcher/src/gql/queries/producer.gql +++ /dev/null @@ -1,10 +0,0 @@ -query producer($id: String!, $block: Block_height){ - producer(id: $id, block: $block){ - id - active - rewardCollector - rewards - confirmedBlocks - pendingEpochBlocks - } -} diff --git a/packages/eden-watcher/src/gql/queries/producerEpoch.gql b/packages/eden-watcher/src/gql/queries/producerEpoch.gql deleted file mode 100644 index 9cd267ee..00000000 --- a/packages/eden-watcher/src/gql/queries/producerEpoch.gql +++ /dev/null @@ -1,17 +0,0 @@ -query producerEpoch($id: String!, $block: Block_height){ - producerEpoch(id: $id, block: $block){ - id - address - epoch{ - id - finalized - epochNumber - producerBlocks - allBlocks - producerBlocksRatio - } - totalRewards - blocksProduced - blocksProducedRatio - } -} diff --git a/packages/eden-watcher/src/gql/queries/producerRewardCollectorChange.gql b/packages/eden-watcher/src/gql/queries/producerRewardCollectorChange.gql deleted file mode 100644 index 249c419c..00000000 --- a/packages/eden-watcher/src/gql/queries/producerRewardCollectorChange.gql +++ /dev/null @@ -1,8 +0,0 @@ -query producerRewardCollectorChange($id: String!, $block: Block_height){ - producerRewardCollectorChange(id: $id, block: $block){ - id - blockNumber - producer - rewardCollector - } -} diff --git a/packages/eden-watcher/src/gql/queries/producerSet.gql b/packages/eden-watcher/src/gql/queries/producerSet.gql deleted file mode 100644 index 33ab6894..00000000 --- a/packages/eden-watcher/src/gql/queries/producerSet.gql +++ /dev/null @@ -1,13 +0,0 @@ -query producerSet($id: String!, $block: Block_height){ - producerSet(id: $id, block: $block){ - id - producers{ - id - active - rewardCollector - rewards - confirmedBlocks - pendingEpochBlocks - } - } -} diff --git a/packages/eden-watcher/src/gql/queries/producerSetChange.gql b/packages/eden-watcher/src/gql/queries/producerSetChange.gql deleted file mode 100644 index 2e79f638..00000000 --- a/packages/eden-watcher/src/gql/queries/producerSetChange.gql +++ /dev/null @@ -1,8 +0,0 @@ -query producerSetChange($id: String!, $block: Block_height){ - producerSetChange(id: $id, block: $block){ - id - blockNumber - producer - changeType - } -} diff --git a/packages/eden-watcher/src/gql/queries/rewardSchedule.gql b/packages/eden-watcher/src/gql/queries/rewardSchedule.gql deleted file mode 100644 index bf4de64a..00000000 --- a/packages/eden-watcher/src/gql/queries/rewardSchedule.gql +++ /dev/null @@ -1,33 +0,0 @@ -query rewardSchedule($id: String!, $block: Block_height){ - rewardSchedule(id: $id, block: $block){ - id - rewardScheduleEntries{ - id - startTime - epochDuration - rewardsPerEpoch - } - lastEpoch{ - id - finalized - epochNumber - producerBlocks - allBlocks - producerBlocksRatio - } - pendingEpoch{ - id - finalized - epochNumber - producerBlocks - allBlocks - producerBlocksRatio - } - activeRewardScheduleEntry{ - id - startTime - epochDuration - rewardsPerEpoch - } - } -} diff --git a/packages/eden-watcher/src/gql/queries/rewardScheduleEntry.gql b/packages/eden-watcher/src/gql/queries/rewardScheduleEntry.gql deleted file mode 100644 index ecf4aee2..00000000 --- a/packages/eden-watcher/src/gql/queries/rewardScheduleEntry.gql +++ /dev/null @@ -1,8 +0,0 @@ -query rewardScheduleEntry($id: String!, $block: Block_height){ - rewardScheduleEntry(id: $id, block: $block){ - id - startTime - epochDuration - rewardsPerEpoch - } -} diff --git a/packages/eden-watcher/src/gql/queries/slash.gql b/packages/eden-watcher/src/gql/queries/slash.gql deleted file mode 100644 index 2e9692a1..00000000 --- a/packages/eden-watcher/src/gql/queries/slash.gql +++ /dev/null @@ -1,12 +0,0 @@ -query slash($id: String!, $block: Block_height){ - slash(id: $id, block: $block){ - id - timestamp - account{ - id - totalClaimed - totalSlashed - } - slashed - } -} diff --git a/packages/eden-watcher/src/gql/queries/slot.gql b/packages/eden-watcher/src/gql/queries/slot.gql deleted file mode 100644 index e9c94fb3..00000000 --- a/packages/eden-watcher/src/gql/queries/slot.gql +++ /dev/null @@ -1,21 +0,0 @@ -query slot($id: String!, $block: Block_height){ - slot(id: $id, block: $block){ - id - owner - delegate - winningBid - oldBid - startTime - expirationTime - taxRatePerDay - claims{ - id - owner - winningBid - oldBid - startTime - expirationTime - taxRatePerDay - } - } -} diff --git a/packages/eden-watcher/src/gql/queries/slotClaim.gql b/packages/eden-watcher/src/gql/queries/slotClaim.gql deleted file mode 100644 index 92ddf9ad..00000000 --- a/packages/eden-watcher/src/gql/queries/slotClaim.gql +++ /dev/null @@ -1,21 +0,0 @@ -query slotClaim($id: String!, $block: Block_height){ - slotClaim(id: $id, block: $block){ - id - slot{ - id - owner - delegate - winningBid - oldBid - startTime - expirationTime - taxRatePerDay - } - owner - winningBid - oldBid - startTime - expirationTime - taxRatePerDay - } -} diff --git a/packages/eden-watcher/src/gql/queries/staker.gql b/packages/eden-watcher/src/gql/queries/staker.gql deleted file mode 100644 index bb4cdd51..00000000 --- a/packages/eden-watcher/src/gql/queries/staker.gql +++ /dev/null @@ -1,7 +0,0 @@ -query staker($id: String!, $block: Block_height){ - staker(id: $id, block: $block){ - id - staked - rank - } -} diff --git a/packages/eden-watcher/src/gql/subscriptions/index.ts b/packages/eden-watcher/src/gql/subscriptions/index.ts deleted file mode 100644 index f12910c5..00000000 --- a/packages/eden-watcher/src/gql/subscriptions/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -import fs from 'fs'; -import path from 'path'; - -export const onEvent = fs.readFileSync(path.join(__dirname, 'onEvent.gql'), 'utf8'); diff --git a/packages/eden-watcher/src/gql/subscriptions/onEvent.gql b/packages/eden-watcher/src/gql/subscriptions/onEvent.gql deleted file mode 100644 index cc42b1ee..00000000 --- a/packages/eden-watcher/src/gql/subscriptions/onEvent.gql +++ /dev/null @@ -1,142 +0,0 @@ -subscription onEvent{ - onEvent{ - block{ - cid - hash - number - timestamp - parentHash - } - tx{ - hash - index - from - to - } - contract - eventIndex - event{ - ... on TransferEvent { - from - to - value - tokenId - } - ... on ApprovalEvent { - owner - spender - value - approved - tokenId - } - ... on AuthorizationUsedEvent { - authorizer - nonce - } - ... on AdminUpdatedEvent { - newAdmin - oldAdmin - } - ... on TaxRateUpdatedEvent { - newNumerator - newDenominator - oldNumerator - oldDenominator - } - ... on SlotClaimedEvent { - slot - owner - delegate - newBidAmount - oldBidAmount - taxNumerator - taxDenominator - } - ... on SlotDelegateUpdatedEvent { - slot - owner - newDelegate - oldDelegate - } - ... on StakeEvent { - staker - stakeAmount - } - ... on UnstakeEvent { - staker - unstakedAmount - } - ... on WithdrawEvent { - withdrawer - withdrawalAmount - } - ... on ApprovalForAllEvent { - owner - operator - approved - } - ... on BlockProducerAddedEvent { - producer - } - ... on BlockProducerRemovedEvent { - producer - } - ... on BlockProducerRewardCollectorChangedEvent { - producer - collector - } - ... on RewardScheduleChangedEvent { - dummy - } - ... on ClaimedEvent { - index - totalEarned - account - claimed - } - ... on SlashedEvent { - account - slashed - } - ... on MerkleRootUpdatedEvent { - merkleRoot - distributionNumber - metadataURI - } - ... on AccountUpdatedEvent { - account - totalClaimed - totalSlashed - } - ... on PermanentURIEvent { - value - id - } - ... on GovernanceChangedEvent { - from - to - } - ... on UpdateThresholdChangedEvent { - updateThreshold - } - ... on RoleAdminChangedEvent { - role - previousAdminRole - newAdminRole - } - ... on RoleGrantedEvent { - role - account - sender - } - ... on RoleRevokedEvent { - role - account - sender - } - } - proof{ - data - } - } -} diff --git a/packages/eden-watcher/src/hooks.ts b/packages/eden-watcher/src/hooks.ts deleted file mode 100644 index 0d8a2876..00000000 --- a/packages/eden-watcher/src/hooks.ts +++ /dev/null @@ -1,71 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; - -import { ResultEvent } from '@cerc-io/util'; - -import { Indexer } from './indexer'; - -/** - * Hook function to store an initial state. - * @param indexer Indexer instance. - * @param blockHash Hash of the concerned block. - * @param contractAddress Address of the concerned contract. - * @returns Data block to be stored. - */ -export async function createInitialState (indexer: Indexer, contractAddress: string, blockHash: string): Promise { - assert(indexer); - assert(blockHash); - assert(contractAddress); - - // Store an empty State. - const stateData: any = { - state: {} - }; - - // Return initial state data to be saved. - return stateData; -} - -/** - * Hook function to create state diff. - * @param indexer Indexer instance that contains methods to fetch the contract varaiable values. - * @param blockHash Block hash of the concerned block. - */ -export async function createStateDiff (indexer: Indexer, blockHash: string): Promise { - assert(indexer); - assert(blockHash); - - // Use indexer.createDiff() method to save custom state diff(s). -} - -/** - * Hook function to create state checkpoint - * @param indexer Indexer instance. - * @param contractAddress Address of the concerned contract. - * @param blockHash Block hash of the concerned block. - * @returns Whether to disable default checkpoint. If false, the state from this hook is updated with that from default checkpoint. - */ -export async function createStateCheckpoint (indexer: Indexer, contractAddress: string, blockHash: string): Promise { - assert(indexer); - assert(blockHash); - assert(contractAddress); - - // Use indexer.createStateCheckpoint() method to create a custom checkpoint. - - // Return false to update the state created by this hook by auto-generated checkpoint state. - // Return true to disable update of the state created by this hook by auto-generated checkpoint state. - return false; -} - -/** - * Event hook function. - * @param indexer Indexer instance that contains methods to fetch and update the contract values in the database. - * @param eventData ResultEvent object containing event information. - */ -export async function handleEvent (indexer: Indexer, eventData: ResultEvent): Promise { - assert(indexer); - assert(eventData); -} diff --git a/packages/eden-watcher/src/indexer.ts b/packages/eden-watcher/src/indexer.ts deleted file mode 100644 index ebbcd995..00000000 --- a/packages/eden-watcher/src/indexer.ts +++ /dev/null @@ -1,941 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import { DeepPartial, FindConditions, FindManyOptions, ObjectLiteral } from 'typeorm'; -import { ethers } from 'ethers'; -import { SelectionNode } from 'graphql'; - -import { JsonFragment } from '@ethersproject/abi'; -import { BaseProvider } from '@ethersproject/providers'; -import { EthClient } from '@cerc-io/ipld-eth-client'; -import { MappingKey, StorageLayout } from '@cerc-io/solidity-mapper'; -import { - Indexer as BaseIndexer, - ServerConfig, - JobQueue, - Where, - QueryOptions, - BlockHeight, - StateKind, - IndexerInterface, - StateStatus, - ValueResult, - ResultEvent, - getResultEvent, - DatabaseInterface, - Clients, - GraphWatcherInterface, - updateSubgraphState, - dumpSubgraphState -} from '@cerc-io/util'; -import { GraphWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITIES, SUBGRAPH_ENTITIES } from './database'; -import { Contract } from './entity/Contract'; -import { Event } from './entity/Event'; -import { SyncStatus } from './entity/SyncStatus'; -import { StateSyncStatus } from './entity/StateSyncStatus'; -import { BlockProgress } from './entity/BlockProgress'; -import { State } from './entity/State'; -import EdenNetworkArtifacts from './artifacts/EdenNetwork.json'; -import MerkleDistributorArtifacts from './artifacts/MerkleDistributor.json'; -import DistributorGovernanceArtifacts from './artifacts/DistributorGovernance.json'; -import { createInitialState, handleEvent, createStateDiff, createStateCheckpoint } from './hooks'; -import { ProducerSet } from './entity/ProducerSet'; -import { Producer } from './entity/Producer'; -import { RewardSchedule } from './entity/RewardSchedule'; -import { RewardScheduleEntry } from './entity/RewardScheduleEntry'; -import { Network } from './entity/Network'; -import { Staker } from './entity/Staker'; -import { ProducerEpoch } from './entity/ProducerEpoch'; -import { Epoch } from './entity/Epoch'; -import { Block } from './entity/Block'; -import { SlotClaim } from './entity/SlotClaim'; -import { Slot } from './entity/Slot'; -import { Distributor } from './entity/Distributor'; -import { Distribution } from './entity/Distribution'; -import { Claim } from './entity/Claim'; -import { Account } from './entity/Account'; -import { Slash } from './entity/Slash'; -import { FrothyEntity } from './entity/FrothyEntity'; - -const KIND_EDENNETWORK = 'EdenNetwork'; -const KIND_MERKLEDISTRIBUTOR = 'EdenNetworkDistribution'; -const KIND_DISTRIBUTORGOVERNANCE = 'EdenNetworkGovernance'; - -export class Indexer implements IndexerInterface { - _db: Database; - _ethClient: EthClient; - _ethProvider: BaseProvider; - _baseIndexer: BaseIndexer; - _serverConfig: ServerConfig; - _graphWatcher: GraphWatcher; - - _abiMap: Map; - _storageLayoutMap: Map; - _contractMap: Map; - - _entityTypesMap: Map; - _relationsMap: Map; - - _subgraphStateMap: Map; - - constructor (serverConfig: ServerConfig, db: DatabaseInterface, clients: Clients, ethProvider: BaseProvider, jobQueue: JobQueue, graphWatcher?: GraphWatcherInterface) { - assert(db); - assert(clients.ethClient); - - this._db = db as Database; - this._ethClient = clients.ethClient; - this._ethProvider = ethProvider; - this._serverConfig = serverConfig; - this._baseIndexer = new BaseIndexer(this._serverConfig, this._db, this._ethClient, this._ethProvider, jobQueue); - - assert(graphWatcher); - this._graphWatcher = graphWatcher as GraphWatcher; - - this._abiMap = new Map(); - this._storageLayoutMap = new Map(); - this._contractMap = new Map(); - - const { abi: EdenNetworkABI, storageLayout: EdenNetworkStorageLayout } = EdenNetworkArtifacts; - const { abi: MerkleDistributorABI, storageLayout: MerkleDistributorStorageLayout } = MerkleDistributorArtifacts; - const { abi: DistributorGovernanceABI, storageLayout: DistributorGovernanceStorageLayout } = DistributorGovernanceArtifacts; - - assert(EdenNetworkABI); - assert(EdenNetworkStorageLayout); - - assert(MerkleDistributorABI); - assert(MerkleDistributorStorageLayout); - - assert(DistributorGovernanceABI); - assert(DistributorGovernanceStorageLayout); - - this._abiMap.set(KIND_EDENNETWORK, EdenNetworkABI); - this._storageLayoutMap.set(KIND_EDENNETWORK, EdenNetworkStorageLayout); - this._contractMap.set(KIND_EDENNETWORK, new ethers.utils.Interface(EdenNetworkABI)); - - this._abiMap.set(KIND_MERKLEDISTRIBUTOR, MerkleDistributorABI); - this._storageLayoutMap.set(KIND_MERKLEDISTRIBUTOR, MerkleDistributorStorageLayout); - this._contractMap.set(KIND_MERKLEDISTRIBUTOR, new ethers.utils.Interface(MerkleDistributorABI)); - - this._abiMap.set(KIND_DISTRIBUTORGOVERNANCE, DistributorGovernanceABI); - this._storageLayoutMap.set(KIND_DISTRIBUTORGOVERNANCE, DistributorGovernanceStorageLayout); - this._contractMap.set(KIND_DISTRIBUTORGOVERNANCE, new ethers.utils.Interface(DistributorGovernanceABI)); - - this._entityTypesMap = new Map(); - this._populateEntityTypesMap(); - - this._relationsMap = new Map(); - this._populateRelationsMap(); - - this._subgraphStateMap = new Map(); - } - - get serverConfig (): ServerConfig { - return this._serverConfig; - } - - get storageLayoutMap (): Map { - return this._storageLayoutMap; - } - - get graphWatcher (): GraphWatcher { - return this._graphWatcher; - } - - async init (): Promise { - await this._baseIndexer.fetchContracts(); - await this._baseIndexer.fetchStateStatus(); - } - - getResultEvent (event: Event): ResultEvent { - return getResultEvent(event); - } - - async getStorageValue (storageLayout: StorageLayout, blockHash: string, contractAddress: string, variable: string, ...mappingKeys: MappingKey[]): Promise { - return this._baseIndexer.getStorageValue( - storageLayout, - blockHash, - contractAddress, - variable, - ...mappingKeys - ); - } - - async getEntitiesForBlock (blockHash: string, tableName: string): Promise { - return this._db.getEntitiesForBlock(blockHash, tableName); - } - - async processInitialState (contractAddress: string, blockHash: string): Promise { - // Call initial state hook. - return createInitialState(this, contractAddress, blockHash); - } - - async processStateCheckpoint (contractAddress: string, blockHash: string): Promise { - // Call checkpoint hook. - return createStateCheckpoint(this, contractAddress, blockHash); - } - - async processCanonicalBlock (blockHash: string, blockNumber: number): Promise { - console.time('time:indexer#processCanonicalBlock-finalize_auto_diffs'); - // Finalize staged diff blocks if any. - await this._baseIndexer.finalizeDiffStaged(blockHash); - console.timeEnd('time:indexer#processCanonicalBlock-finalize_auto_diffs'); - - // Call custom stateDiff hook. - await createStateDiff(this, blockHash); - - this._graphWatcher.pruneEntityCacheFrothyBlocks(blockHash, blockNumber); - } - - async processCheckpoint (blockHash: string): Promise { - // Return if checkpointInterval is <= 0. - const checkpointInterval = this._serverConfig.checkpointInterval; - if (checkpointInterval <= 0) return; - - console.time('time:indexer#processCheckpoint-checkpoint'); - - await this._baseIndexer.processCheckpoint(this, blockHash, checkpointInterval); - - console.timeEnd('time:indexer#processCheckpoint-checkpoint'); - } - - async processCLICheckpoint (contractAddress: string, blockHash?: string): Promise { - return this._baseIndexer.processCLICheckpoint(this, contractAddress, blockHash); - } - - async getPrevState (blockHash: string, contractAddress: string, kind?: string): Promise { - return this._db.getPrevState(blockHash, contractAddress, kind); - } - - async getLatestState (contractAddress: string, kind: StateKind | null, blockNumber?: number): Promise { - return this._db.getLatestState(contractAddress, kind, blockNumber); - } - - async getStatesByHash (blockHash: string): Promise { - return this._baseIndexer.getStatesByHash(blockHash); - } - - async getStateByCID (cid: string): Promise { - return this._baseIndexer.getStateByCID(cid); - } - - async getStates (where: FindConditions): Promise { - return this._db.getStates(where); - } - - async getDiffStatesInRange (contractAddress: string, startBlock: number, endBlock: number): Promise { - return this._db.getDiffStatesInRange(contractAddress, startBlock, endBlock); - } - - getStateData (state: State): any { - return this._baseIndexer.getStateData(state); - } - - // Method used to create auto diffs (diff_staged). - async createDiffStaged (contractAddress: string, blockHash: string, data: any): Promise { - console.time('time:indexer#createDiffStaged-auto_diff'); - - await this._baseIndexer.createDiffStaged(contractAddress, blockHash, data); - - console.timeEnd('time:indexer#createDiffStaged-auto_diff'); - } - - // Method to be used by createStateDiff hook. - async createDiff (contractAddress: string, blockHash: string, data: any): Promise { - const block = await this.getBlockProgress(blockHash); - assert(block); - - await this._baseIndexer.createDiff(contractAddress, block, data); - } - - // Method to be used by createStateCheckpoint hook. - async createStateCheckpoint (contractAddress: string, blockHash: string, data: any): Promise { - const block = await this.getBlockProgress(blockHash); - assert(block); - - return this._baseIndexer.createStateCheckpoint(contractAddress, block, data); - } - - // Method to be used by export-state CLI. - async createCheckpoint (contractAddress: string, blockHash: string): Promise { - const block = await this.getBlockProgress(blockHash); - assert(block); - - return this._baseIndexer.createCheckpoint(this, contractAddress, block); - } - - // Method to be used by fill-state CLI. - async createInit (blockHash: string, blockNumber: number): Promise { - // Create initial state for contracts. - await this._baseIndexer.createInit(this, blockHash, blockNumber); - } - - async saveOrUpdateState (state: State): Promise { - return this._baseIndexer.saveOrUpdateState(state); - } - - async removeStates (blockNumber: number, kind: StateKind): Promise { - await this._baseIndexer.removeStates(blockNumber, kind); - } - - async getSubgraphEntity (entity: new () => Entity, id: string, block: BlockHeight, selections: ReadonlyArray = []): Promise { - const data = await this._graphWatcher.getEntity(entity, id, this._relationsMap, block, selections); - - return data; - } - - async getSubgraphEntities ( - entity: new () => Entity, - block: BlockHeight, - where: { [key: string]: any } = {}, - queryOptions: QueryOptions = {}, - selections: ReadonlyArray = [] - ): Promise { - return this._graphWatcher.getEntities(entity, this._relationsMap, block, where, queryOptions, selections); - } - - async triggerIndexingOnEvent (event: Event): Promise { - const resultEvent = this.getResultEvent(event); - - console.time('time:indexer#processEvent-mapping_code'); - - // Call subgraph handler for event. - await this._graphWatcher.handleEvent(resultEvent); - - console.timeEnd('time:indexer#processEvent-mapping_code'); - - // Call custom hook function for indexing on event. - await handleEvent(this, resultEvent); - } - - async processEvent (event: Event): Promise { - // Trigger indexing of data based on the event. - await this.triggerIndexingOnEvent(event); - } - - async processBlock (blockProgress: BlockProgress): Promise { - console.time('time:indexer#processBlock-init_state'); - // Call a function to create initial state for contracts. - await this._baseIndexer.createInit(this, blockProgress.blockHash, blockProgress.blockNumber); - console.timeEnd('time:indexer#processBlock-init_state'); - - this._graphWatcher.updateEntityCacheFrothyBlocks(blockProgress); - } - - async processBlockAfterEvents (blockHash: string, blockNumber: number): Promise { - console.time('time:indexer#processBlockAfterEvents-mapping_code'); - - // Call subgraph handler for block. - await this._graphWatcher.handleBlock(blockHash, blockNumber); - - console.timeEnd('time:indexer#processBlockAfterEvents-mapping_code'); - - console.time('time:indexer#processBlockAfterEvents-dump_subgraph_state'); - - // Persist subgraph state to the DB. - await this.dumpSubgraphState(blockHash); - - console.timeEnd('time:indexer#processBlockAfterEvents-dump_subgraph_state'); - } - - parseEventNameAndArgs (kind: string, logObj: any): any { - const { topics, data } = logObj; - - const contract = this._contractMap.get(kind); - assert(contract); - - const logDescription = contract.parseLog({ data, topics }); - - const { eventName, eventInfo, eventSignature } = this._baseIndexer.parseEvent(logDescription); - - return { - eventName, - eventInfo, - eventSignature - }; - } - - async getStateSyncStatus (): Promise { - return this._db.getStateSyncStatus(); - } - - async updateStateSyncStatusIndexedBlock (blockNumber: number, force?: boolean): Promise { - const dbTx = await this._db.createTransactionRunner(); - let res; - - try { - res = await this._db.updateStateSyncStatusIndexedBlock(dbTx, blockNumber, force); - await dbTx.commitTransaction(); - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - - return res; - } - - async updateStateSyncStatusCheckpointBlock (blockNumber: number, force?: boolean): Promise { - const dbTx = await this._db.createTransactionRunner(); - let res; - - try { - res = await this._db.updateStateSyncStatusCheckpointBlock(dbTx, blockNumber, force); - await dbTx.commitTransaction(); - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - - return res; - } - - async getLatestCanonicalBlock (): Promise { - const syncStatus = await this.getSyncStatus(); - assert(syncStatus); - - const latestCanonicalBlock = await this.getBlockProgress(syncStatus.latestCanonicalBlockHash); - assert(latestCanonicalBlock); - - return latestCanonicalBlock; - } - - async getLatestStateIndexedBlock (): Promise { - return this._baseIndexer.getLatestStateIndexedBlock(); - } - - async addContracts (): Promise { - // Watching all the contracts in the subgraph. - await this._graphWatcher.addContracts(); - } - - async watchContract (address: string, kind: string, checkpoint: boolean, startingBlock: number): Promise { - return this._baseIndexer.watchContract(address, kind, checkpoint, startingBlock); - } - - updateStateStatusMap (address: string, stateStatus: StateStatus): void { - this._baseIndexer.updateStateStatusMap(address, stateStatus); - } - - cacheContract (contract: Contract): void { - return this._baseIndexer.cacheContract(contract); - } - - async saveEventEntity (dbEvent: Event): Promise { - return this._baseIndexer.saveEventEntity(dbEvent); - } - - async getEventsByFilter (blockHash: string, contract?: string, name?: string): Promise> { - return this._baseIndexer.getEventsByFilter(blockHash, contract, name); - } - - isWatchedContract (address : string): Contract | undefined { - return this._baseIndexer.isWatchedContract(address); - } - - async getProcessedBlockCountForRange (fromBlockNumber: number, toBlockNumber: number): Promise<{ expected: number, actual: number }> { - return this._baseIndexer.getProcessedBlockCountForRange(fromBlockNumber, toBlockNumber); - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise> { - return this._baseIndexer.getEventsInRange(fromBlockNumber, toBlockNumber); - } - - async getSyncStatus (): Promise { - return this._baseIndexer.getSyncStatus(); - } - - async getBlocks (blockFilter: { blockHash?: string, blockNumber?: number }): Promise { - return this._baseIndexer.getBlocks(blockFilter); - } - - async updateSyncStatusIndexedBlock (blockHash: string, blockNumber: number, force = false): Promise { - return this._baseIndexer.updateSyncStatusIndexedBlock(blockHash, blockNumber, force); - } - - async updateSyncStatusChainHead (blockHash: string, blockNumber: number, force = false): Promise { - return this._baseIndexer.updateSyncStatusChainHead(blockHash, blockNumber, force); - } - - async updateSyncStatusCanonicalBlock (blockHash: string, blockNumber: number, force = false): Promise { - const syncStatus = this._baseIndexer.updateSyncStatusCanonicalBlock(blockHash, blockNumber, force); - await this.pruneFrothyEntities(blockNumber); - - return syncStatus; - } - - async getEvent (id: string): Promise { - return this._baseIndexer.getEvent(id); - } - - async getBlockProgress (blockHash: string): Promise { - return this._baseIndexer.getBlockProgress(blockHash); - } - - async getBlockProgressEntities (where: FindConditions, options: FindManyOptions): Promise { - return this._baseIndexer.getBlockProgressEntities(where, options); - } - - async getBlocksAtHeight (height: number, isPruned: boolean): Promise { - return this._baseIndexer.getBlocksAtHeight(height, isPruned); - } - - async saveBlockAndFetchEvents (block: DeepPartial): Promise<[BlockProgress, DeepPartial[]]> { - return this._saveBlockAndFetchEvents(block); - } - - async getBlockEvents (blockHash: string, where: Where, queryOptions: QueryOptions): Promise> { - return this._baseIndexer.getBlockEvents(blockHash, where, queryOptions); - } - - async removeUnknownEvents (block: BlockProgress): Promise { - return this._baseIndexer.removeUnknownEvents(Event, block); - } - - async markBlocksAsPruned (blocks: BlockProgress[]): Promise { - await this._baseIndexer.markBlocksAsPruned(blocks); - - await this._graphWatcher.pruneEntities(FrothyEntity, blocks, SUBGRAPH_ENTITIES); - } - - async pruneFrothyEntities (blockNumber: number): Promise { - await this._graphWatcher.pruneFrothyEntities(FrothyEntity, blockNumber); - } - - async resetLatestEntities (blockNumber: number): Promise { - await this._graphWatcher.resetLatestEntities(blockNumber); - - await this.resetLatestEntities(blockNumber); - } - - async updateBlockProgress (block: BlockProgress, lastProcessedEventIndex: number): Promise { - return this._baseIndexer.updateBlockProgress(block, lastProcessedEventIndex); - } - - async getAncestorAtDepth (blockHash: string, depth: number): Promise { - return this._baseIndexer.getAncestorAtDepth(blockHash, depth); - } - - getEntityTypesMap (): Map { - return this._entityTypesMap; - } - - getRelationsMap (): Map { - return this._relationsMap; - } - - updateSubgraphState (contractAddress: string, data: any): void { - return updateSubgraphState(this._subgraphStateMap, contractAddress, data); - } - - async dumpSubgraphState (blockHash: string, isStateFinalized = false): Promise { - return dumpSubgraphState(this, this._subgraphStateMap, blockHash, isStateFinalized); - } - - async resetWatcherToBlock (blockNumber: number): Promise { - const entities = [...ENTITIES, FrothyEntity]; - await this._baseIndexer.resetWatcherToBlock(blockNumber, entities); - } - - _populateEntityTypesMap (): void { - this._entityTypesMap.set( - 'Producer', - { - id: 'ID', - active: 'Boolean', - rewardCollector: 'Bytes', - rewards: 'BigInt', - confirmedBlocks: 'BigInt', - pendingEpochBlocks: 'BigInt' - } - ); - - this._entityTypesMap.set( - 'ProducerSet', - { - id: 'ID', - producers: 'Producer' - } - ); - - this._entityTypesMap.set( - 'ProducerSetChange', - { - id: 'ID', - blockNumber: 'BigInt', - producer: 'Bytes', - changeType: 'ProducerSetChangeType' - } - ); - - this._entityTypesMap.set( - 'ProducerRewardCollectorChange', - { - id: 'ID', - blockNumber: 'BigInt', - producer: 'Bytes', - rewardCollector: 'Bytes' - } - ); - - this._entityTypesMap.set( - 'RewardScheduleEntry', - { - id: 'ID', - startTime: 'BigInt', - epochDuration: 'BigInt', - rewardsPerEpoch: 'BigInt' - } - ); - - this._entityTypesMap.set( - 'RewardSchedule', - { - id: 'ID', - rewardScheduleEntries: 'RewardScheduleEntry', - lastEpoch: 'Epoch', - pendingEpoch: 'Epoch', - activeRewardScheduleEntry: 'RewardScheduleEntry' - } - ); - - this._entityTypesMap.set( - 'Block', - { - id: 'ID', - fromActiveProducer: 'Boolean', - hash: 'Bytes', - parentHash: 'Bytes', - unclesHash: 'Bytes', - author: 'Bytes', - stateRoot: 'Bytes', - transactionsRoot: 'Bytes', - receiptsRoot: 'Bytes', - number: 'BigInt', - gasUsed: 'BigInt', - gasLimit: 'BigInt', - timestamp: 'BigInt', - difficulty: 'BigInt', - totalDifficulty: 'BigInt', - size: 'BigInt' - } - ); - - this._entityTypesMap.set( - 'Epoch', - { - id: 'ID', - finalized: 'Boolean', - epochNumber: 'BigInt', - startBlock: 'Block', - endBlock: 'Block', - producerBlocks: 'BigInt', - allBlocks: 'BigInt', - producerBlocksRatio: 'BigDecimal' - } - ); - - this._entityTypesMap.set( - 'ProducerEpoch', - { - id: 'ID', - address: 'Bytes', - epoch: 'Epoch', - totalRewards: 'BigInt', - blocksProduced: 'BigInt', - blocksProducedRatio: 'BigDecimal' - } - ); - - this._entityTypesMap.set( - 'SlotClaim', - { - id: 'ID', - slot: 'Slot', - owner: 'Bytes', - winningBid: 'BigInt', - oldBid: 'BigInt', - startTime: 'BigInt', - expirationTime: 'BigInt', - taxRatePerDay: 'BigDecimal' - } - ); - - this._entityTypesMap.set( - 'Slot', - { - id: 'ID', - owner: 'Bytes', - delegate: 'Bytes', - winningBid: 'BigInt', - oldBid: 'BigInt', - startTime: 'BigInt', - expirationTime: 'BigInt', - taxRatePerDay: 'BigDecimal' - } - ); - - this._entityTypesMap.set( - 'Staker', - { - id: 'ID', - staked: 'BigInt', - rank: 'BigInt' - } - ); - - this._entityTypesMap.set( - 'Network', - { - id: 'ID', - slot0: 'Slot', - slot1: 'Slot', - slot2: 'Slot', - stakers: 'Staker', - numStakers: 'BigInt', - totalStaked: 'BigInt', - stakedPercentiles: 'BigInt' - } - ); - - this._entityTypesMap.set( - 'Distributor', - { - id: 'ID', - currentDistribution: 'Distribution' - } - ); - - this._entityTypesMap.set( - 'Distribution', - { - id: 'ID', - distributor: 'Distributor', - timestamp: 'BigInt', - distributionNumber: 'BigInt', - merkleRoot: 'Bytes', - metadataURI: 'String' - } - ); - - this._entityTypesMap.set( - 'Claim', - { - id: 'ID', - timestamp: 'BigInt', - index: 'BigInt', - account: 'Account', - totalEarned: 'BigInt', - claimed: 'BigInt' - } - ); - - this._entityTypesMap.set( - 'Account', - { - id: 'ID', - totalClaimed: 'BigInt', - totalSlashed: 'BigInt' - } - ); - - this._entityTypesMap.set( - 'Slash', - { - id: 'ID', - timestamp: 'BigInt', - account: 'Account', - slashed: 'BigInt' - } - ); - } - - _populateRelationsMap (): void { - this._relationsMap.set(ProducerSet, { - producers: { - entity: Producer, - isArray: true, - isDerived: false - } - }); - - this._relationsMap.set(RewardSchedule, { - rewardScheduleEntries: { - entity: RewardScheduleEntry, - isArray: true, - isDerived: false - }, - lastEpoch: { - entity: Epoch, - isArray: false, - isDerived: false - }, - pendingEpoch: { - entity: Epoch, - isArray: false, - isDerived: false - }, - activeRewardScheduleEntry: { - entity: RewardScheduleEntry, - isArray: false, - isDerived: false - } - }); - - this._relationsMap.set(ProducerEpoch, { - epoch: { - entity: Epoch, - isArray: false, - isDerived: false - } - }); - - this._relationsMap.set(Epoch, { - startBlock: { - entity: Block, - isArray: false, - isDerived: false - }, - endBlock: { - entity: Block, - isArray: false, - isDerived: false - }, - producerRewards: { - entity: ProducerEpoch, - isArray: true, - isDerived: true, - field: 'epoch' - } - }); - - this._relationsMap.set(SlotClaim, { - slot: { - entity: Slot, - isArray: false, - isDerived: false - } - }); - - this._relationsMap.set(Network, { - slot0: { - entity: Slot, - isArray: false, - isDerived: false - }, - slot1: { - entity: Slot, - isArray: false, - isDerived: false - }, - slot2: { - entity: Slot, - isArray: false, - isDerived: false - }, - stakers: { - entity: Staker, - isArray: true, - isDerived: false - } - }); - - this._relationsMap.set(Distributor, { - currentDistribution: { - entity: Distribution, - isArray: false, - isDerived: false - } - }); - - this._relationsMap.set(Distribution, { - distributor: { - entity: Distributor, - isArray: false, - isDerived: false - } - }); - - this._relationsMap.set(Claim, { - account: { - entity: Account, - isArray: false, - isDerived: false - } - }); - - this._relationsMap.set(Slash, { - account: { - entity: Account, - isArray: false, - isDerived: false - } - }); - - this._relationsMap.set(Slot, { - claims: { - entity: SlotClaim, - isArray: true, - isDerived: true, - field: 'slot' - } - }); - - this._relationsMap.set(Account, { - claims: { - entity: Claim, - isArray: true, - isDerived: true, - field: 'account' - }, - slashes: { - entity: Slash, - isArray: true, - isDerived: true, - field: 'account' - } - }); - } - - async _saveBlockAndFetchEvents ({ - cid: blockCid, - blockHash, - blockNumber, - blockTimestamp, - parentHash - }: DeepPartial): Promise<[BlockProgress, DeepPartial[]]> { - assert(blockHash); - assert(blockNumber); - - const dbEvents = await this._baseIndexer.fetchEvents(blockHash, blockNumber, this.parseEventNameAndArgs.bind(this)); - - const dbTx = await this._db.createTransactionRunner(); - try { - const block = { - cid: blockCid, - blockHash, - blockNumber, - blockTimestamp, - parentHash - }; - - console.time(`time:indexer#_saveBlockAndFetchEvents-db-save-${blockNumber}`); - const blockProgress = await this._db.saveBlockWithEvents(dbTx, block, dbEvents); - await dbTx.commitTransaction(); - console.timeEnd(`time:indexer#_saveBlockAndFetchEvents-db-save-${blockNumber}`); - - return [blockProgress, []]; - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - } -} diff --git a/packages/eden-watcher/src/job-runner.ts b/packages/eden-watcher/src/job-runner.ts deleted file mode 100644 index 84b0065e..00000000 --- a/packages/eden-watcher/src/job-runner.ts +++ /dev/null @@ -1,47 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import debug from 'debug'; - -import { JobRunnerCmd } from '@cerc-io/cli'; -import { JobRunner } from '@cerc-io/util'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Indexer } from './indexer'; -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from './database'; - -const log = debug('vulcanize:job-runner'); - -export const main = async (): Promise => { - const jobRunnerCmd = new JobRunnerCmd(); - await jobRunnerCmd.init(Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - jobRunnerCmd.config.server, - jobRunnerCmd.clients.ethClient, - jobRunnerCmd.ethProvider, - jobRunnerCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await jobRunnerCmd.initIndexer(Indexer, graphWatcher); - - await jobRunnerCmd.exec(async (jobRunner: JobRunner): Promise => { - await jobRunner.subscribeBlockProcessingQueue(); - await jobRunner.subscribeEventProcessingQueue(); - await jobRunner.subscribeBlockCheckpointQueue(); - await jobRunner.subscribeHooksQueue(); - }); -}; - -main().then(() => { - log('Starting job runner...'); -}).catch(err => { - log(err); -}); - -process.on('uncaughtException', err => { - log('uncaughtException', err); -}); diff --git a/packages/eden-watcher/src/resolvers.ts b/packages/eden-watcher/src/resolvers.ts deleted file mode 100644 index bf1c1283..00000000 --- a/packages/eden-watcher/src/resolvers.ts +++ /dev/null @@ -1,532 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import BigInt from 'apollo-type-bigint'; -import debug from 'debug'; -import Decimal from 'decimal.js'; -import { GraphQLResolveInfo, GraphQLScalarType } from 'graphql'; - -import { BlockHeight, OrderDirection, gqlTotalQueryCount, gqlQueryCount, jsonBigIntStringReplacer, getResultState, setGQLCacheHints, IndexerInterface, EventWatcher } from '@cerc-io/util'; - -import { Indexer } from './indexer'; -import { Producer } from './entity/Producer'; -import { ProducerSet } from './entity/ProducerSet'; -import { ProducerSetChange } from './entity/ProducerSetChange'; -import { ProducerRewardCollectorChange } from './entity/ProducerRewardCollectorChange'; -import { RewardScheduleEntry } from './entity/RewardScheduleEntry'; -import { RewardSchedule } from './entity/RewardSchedule'; -import { ProducerEpoch } from './entity/ProducerEpoch'; -import { Block } from './entity/Block'; -import { Epoch } from './entity/Epoch'; -import { SlotClaim } from './entity/SlotClaim'; -import { Slot } from './entity/Slot'; -import { Staker } from './entity/Staker'; -import { Network } from './entity/Network'; -import { Distributor } from './entity/Distributor'; -import { Distribution } from './entity/Distribution'; -import { Claim } from './entity/Claim'; -import { Slash } from './entity/Slash'; -import { Account } from './entity/Account'; - -const log = debug('vulcanize:resolver'); - -export const createResolvers = async (indexerArg: IndexerInterface, eventWatcher: EventWatcher): Promise => { - const indexer = indexerArg as Indexer; - - const gqlCacheConfig = indexer.serverConfig.gqlCache; - - return { - BigInt: new BigInt('bigInt'), - - BigDecimal: new GraphQLScalarType({ - name: 'BigDecimal', - description: 'BigDecimal custom scalar type', - parseValue (value) { - // value from the client - return new Decimal(value); - }, - serialize (value: Decimal) { - // value sent to the client - return value.toFixed(); - } - }), - - Event: { - __resolveType: (obj: any) => { - assert(obj.__typename); - - return obj.__typename; - } - }, - - Subscription: { - onEvent: { - subscribe: () => eventWatcher.getEventIterator() - } - }, - - Mutation: { - watchContract: async (_: any, { address, kind, checkpoint, startingBlock = 1 }: { address: string, kind: string, checkpoint: boolean, startingBlock: number }): Promise => { - log('watchContract', address, kind, checkpoint, startingBlock); - await indexer.watchContract(address, kind, checkpoint, startingBlock); - - return true; - } - }, - - Query: { - producer: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('producer', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('producer').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(Producer, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - producers: async ( - _: any, - { block = {}, first, skip }: { block: BlockHeight, first: number, skip: number }, - __: any, - info: GraphQLResolveInfo - ) => { - log('producers', JSON.stringify(block, jsonBigIntStringReplacer), first, skip); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('producers').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntities( - Producer, - block, - {}, - { limit: first, skip }, - info.fieldNodes[0].selectionSet.selections - ); - }, - - producerSet: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('producerSet', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('producerSet').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(ProducerSet, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - producerSetChange: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('producerSetChange', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('producerSetChange').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(ProducerSetChange, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - producerRewardCollectorChange: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('producerRewardCollectorChange', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('producerRewardCollectorChange').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(ProducerRewardCollectorChange, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - rewardScheduleEntry: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('rewardScheduleEntry', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('rewardScheduleEntry').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(RewardScheduleEntry, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - rewardSchedule: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('rewardSchedule', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('rewardSchedule').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(RewardSchedule, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - producerEpoch: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('producerEpoch', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('producerEpoch').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(ProducerEpoch, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - block: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('block', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('block').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(Block, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - blocks: async ( - _: any, - { block = {}, where, first, skip, orderBy, orderDirection }: { block: BlockHeight, where: { [key: string]: any }, first: number, skip: number, orderBy: string, orderDirection: OrderDirection }, - __: any, - info: GraphQLResolveInfo - ) => { - log('blocks', JSON.stringify(block, jsonBigIntStringReplacer), JSON.stringify(where, jsonBigIntStringReplacer), first, skip, orderBy, orderDirection); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('blocks').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntities( - Block, - block, - where, - { limit: first, skip, orderBy, orderDirection }, - info.fieldNodes[0].selectionSet.selections - ); - }, - - epoch: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('epoch', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('epoch').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(Epoch, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - epoches: async ( - _: any, - { block = {}, where, first, skip }: { block: BlockHeight, where: { [key: string]: any }, first: number, skip: number }, - __: any, - info: GraphQLResolveInfo - ) => { - log('epoches', JSON.stringify(block, jsonBigIntStringReplacer), JSON.stringify(where, jsonBigIntStringReplacer), first, skip); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('epoches').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntities( - Epoch, - block, - where, - { limit: first, skip }, - info.fieldNodes[0].selectionSet.selections - ); - }, - - slotClaim: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('slotClaim', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('slotClaim').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(SlotClaim, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - slot: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('slot', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('slot').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(Slot, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - staker: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('staker', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('staker').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(Staker, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - stakers: async ( - _: any, - { block = {}, where, first, skip, orderBy, orderDirection }: { block: BlockHeight, where: { [key: string]: any }, first: number, skip: number, orderBy: string, orderDirection: OrderDirection }, - __: any, - info: GraphQLResolveInfo - ) => { - log('stakers', JSON.stringify(block, jsonBigIntStringReplacer), JSON.stringify(where, jsonBigIntStringReplacer), first, skip, orderBy, orderDirection); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('stakers').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntities( - Staker, - block, - where, - { limit: first, skip, orderBy, orderDirection }, - info.fieldNodes[0].selectionSet.selections - ); - }, - - network: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('network', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('network').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(Network, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - distributor: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('distributor', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('distributor').inc(1); - assert(info.fieldNodes[0].selectionSet); - - return indexer.getSubgraphEntity(Distributor, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - distribution: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('distribution', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('distribution').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(Distribution, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - claim: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('claim', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('claim').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(Claim, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - slash: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('slash', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('slash').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(Slash, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - account: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('account', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('account').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(Account, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - events: async (_: any, { blockHash, contractAddress, name }: { blockHash: string, contractAddress: string, name?: string }) => { - log('events', blockHash, contractAddress, name); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('events').inc(1); - - const block = await indexer.getBlockProgress(blockHash); - if (!block || !block.isComplete) { - throw new Error(`Block hash ${blockHash} number ${block?.blockNumber} not processed yet`); - } - - const events = await indexer.getEventsByFilter(blockHash, contractAddress, name); - return events.map(event => indexer.getResultEvent(event)); - }, - - eventsInRange: async (_: any, { fromBlockNumber, toBlockNumber }: { fromBlockNumber: number, toBlockNumber: number }) => { - log('eventsInRange', fromBlockNumber, toBlockNumber); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('eventsInRange').inc(1); - - const { expected, actual } = await indexer.getProcessedBlockCountForRange(fromBlockNumber, toBlockNumber); - if (expected !== actual) { - throw new Error(`Range not available, expected ${expected}, got ${actual} blocks in range`); - } - - const events = await indexer.getEventsInRange(fromBlockNumber, toBlockNumber); - return events.map(event => indexer.getResultEvent(event)); - }, - - getStateByCID: async (_: any, { cid }: { cid: string }) => { - log('getStateByCID', cid); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('getStateByCID').inc(1); - - const state = await indexer.getStateByCID(cid); - - return state && state.block.isComplete ? getResultState(state) : undefined; - }, - - getState: async (_: any, { blockHash, contractAddress, kind }: { blockHash: string, contractAddress: string, kind: string }) => { - log('getState', blockHash, contractAddress, kind); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('getState').inc(1); - - const state = await indexer.getPrevState(blockHash, contractAddress, kind); - - return state && state.block.isComplete ? getResultState(state) : undefined; - }, - - getSyncStatus: async () => { - log('getSyncStatus'); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('getSyncStatus').inc(1); - - return indexer.getSyncStatus(); - } - } - }; -}; diff --git a/packages/eden-watcher/src/schema.gql b/packages/eden-watcher/src/schema.gql deleted file mode 100644 index 1790d1ab..00000000 --- a/packages/eden-watcher/src/schema.gql +++ /dev/null @@ -1,464 +0,0 @@ -enum CacheControlScope { - PUBLIC - PRIVATE -} - -directive @cacheControl( - maxAge: Int - scope: CacheControlScope - inheritMaxAge: Boolean -) on FIELD_DEFINITION | OBJECT | INTERFACE | UNION - -scalar BigInt - -scalar Bytes - -scalar BigDecimal - -input Block_height { - hash: Bytes - number: Int -} - -type Proof { - data: String! -} - -type ResultBoolean { - value: Boolean! - proof: Proof -} - -type ResultString { - value: String! - proof: Proof -} - -type ResultInt { - value: Int! - proof: Proof -} - -type ResultBigInt { - value: BigInt! - proof: Proof -} - -type _Block_ { - cid: String! - hash: String! - number: Int! - timestamp: Int! - parentHash: String! -} - -type _Transaction_ { - hash: String! - index: Int! - from: String! - to: String! -} - -type ResultEvent { - block: _Block_! - tx: _Transaction_! - contract: String! - eventIndex: Int! - event: Event! - proof: Proof -} - -union Event = TransferEvent | ApprovalEvent | AuthorizationUsedEvent | AdminUpdatedEvent | TaxRateUpdatedEvent | SlotClaimedEvent | SlotDelegateUpdatedEvent | StakeEvent | UnstakeEvent | WithdrawEvent | ApprovalForAllEvent | BlockProducerAddedEvent | BlockProducerRemovedEvent | BlockProducerRewardCollectorChangedEvent | ClaimedEvent | SlashedEvent | MerkleRootUpdatedEvent | AccountUpdatedEvent | PermanentURIEvent | GovernanceChangedEvent | UpdateThresholdChangedEvent | RoleAdminChangedEvent | RoleGrantedEvent | RoleRevokedEvent | RewardScheduleChangedEvent - -type TransferEvent { - from: String! - to: String! - value: BigInt - tokenId: BigInt -} - -type ApprovalEvent { - owner: String! - spender: String - value: BigInt - approved: String - tokenId: BigInt -} - -type AuthorizationUsedEvent { - authorizer: String! - nonce: String! -} - -type AdminUpdatedEvent { - newAdmin: String! - oldAdmin: String! -} - -type TaxRateUpdatedEvent { - newNumerator: Int! - newDenominator: Int! - oldNumerator: Int! - oldDenominator: Int! -} - -type SlotClaimedEvent { - slot: Int! - owner: String! - delegate: String! - newBidAmount: BigInt! - oldBidAmount: BigInt! - taxNumerator: Int! - taxDenominator: Int! -} - -type SlotDelegateUpdatedEvent { - slot: Int! - owner: String! - newDelegate: String! - oldDelegate: String! -} - -type StakeEvent { - staker: String! - stakeAmount: BigInt! -} - -type UnstakeEvent { - staker: String! - unstakedAmount: BigInt! -} - -type WithdrawEvent { - withdrawer: String! - withdrawalAmount: BigInt! -} - -type ApprovalForAllEvent { - owner: String! - operator: String! - approved: Boolean! -} - -type BlockProducerAddedEvent { - producer: String! -} - -type BlockProducerRemovedEvent { - producer: String! -} - -type BlockProducerRewardCollectorChangedEvent { - producer: String! - collector: String! -} - -type RewardScheduleChangedEvent { - # Note: dummy property added as server throws an error for type without any fields. - dummy: String -} - -type ClaimedEvent { - index: BigInt! - totalEarned: BigInt! - account: String! - claimed: BigInt! -} - -type SlashedEvent { - account: String! - slashed: BigInt! -} - -type MerkleRootUpdatedEvent { - merkleRoot: String! - distributionNumber: BigInt! - metadataURI: String! -} - -type AccountUpdatedEvent { - account: String! - totalClaimed: BigInt! - totalSlashed: BigInt! -} - -type PermanentURIEvent { - value: String! - id: BigInt! -} - -type GovernanceChangedEvent { - from: String! - to: String! -} - -type UpdateThresholdChangedEvent { - updateThreshold: BigInt! -} - -type RoleAdminChangedEvent { - role: String! - previousAdminRole: String! - newAdminRole: String! -} - -type RoleGrantedEvent { - role: String! - account: String! - sender: String! -} - -type RoleRevokedEvent { - role: String! - account: String! - sender: String! -} - -type ResultState { - block: _Block_! - contractAddress: String! - cid: String! - kind: String! - data: String! -} - -type SyncStatus { - latestIndexedBlockHash: String! - latestIndexedBlockNumber: Int! - latestCanonicalBlockHash: String! - latestCanonicalBlockNumber: Int! -} - -enum OrderDirection { - asc - desc -} - -type Query { - events(blockHash: String!, contractAddress: String!, name: String): [ResultEvent!] - eventsInRange(fromBlockNumber: Int!, toBlockNumber: Int!): [ResultEvent!] - producer(id: String!, block: Block_height): Producer! - producers(block: Block_height, first: Int = 100, skip: Int = 0): [Producer!]! - producerSet(id: String!, block: Block_height): ProducerSet! - producerSetChange(id: String!, block: Block_height): ProducerSetChange! - producerRewardCollectorChange(id: String!, block: Block_height): ProducerRewardCollectorChange! - rewardScheduleEntry(id: String!, block: Block_height): RewardScheduleEntry! - rewardSchedule(id: String!, block: Block_height): RewardSchedule! - producerEpoch(id: String!, block: Block_height): ProducerEpoch! - block(id: String!, block: Block_height): Block! - blocks(where: Block_filter, block: Block_height, orderBy: Block_orderBy, orderDirection: OrderDirection, first: Int = 100, skip: Int = 0): [Block!]! - epoch(id: String!, block: Block_height): Epoch! - epoches(where: Epoch_filter, block: Block_height, first: Int = 100, skip: Int = 0): [Epoch!]! - slotClaim(id: String!, block: Block_height): SlotClaim! - slot(id: String!, block: Block_height): Slot! - staker(id: String!, block: Block_height): Staker! - stakers(where: Staker_filter, block: Block_height, orderBy: Staker_orderBy, orderDirection: OrderDirection, first: Int = 100, skip: Int = 0): [Staker!]! - network(id: String!, block: Block_height): Network! - distributor(id: String!, block: Block_height): Distributor! - distribution(id: String!, block: Block_height): Distribution! - claim(id: String!, block: Block_height): Claim! - slash(id: String!, block: Block_height): Slash! - account(id: String!, block: Block_height): Account! - getStateByCID(cid: String!): ResultState - getState(blockHash: String!, contractAddress: String!, kind: String): ResultState - getSyncStatus: SyncStatus -} - -type Producer { - id: ID! - active: Boolean! - rewardCollector: Bytes - rewards: BigInt! - confirmedBlocks: BigInt! - pendingEpochBlocks: BigInt! -} - -type ProducerSet { - id: ID! - producers: [Producer!]! @cacheControl(inheritMaxAge: true) -} - -type ProducerSetChange { - id: ID! - blockNumber: BigInt! - producer: Bytes! - changeType: ProducerSetChangeType! @cacheControl(inheritMaxAge: true) -} - -enum ProducerSetChangeType { - Added - Removed -} - -type ProducerRewardCollectorChange { - id: ID! - blockNumber: BigInt! - producer: Bytes! - rewardCollector: Bytes! -} - -type RewardScheduleEntry { - id: ID! - startTime: BigInt! - epochDuration: BigInt! - rewardsPerEpoch: BigInt! -} - -type RewardSchedule { - id: ID! - rewardScheduleEntries: [RewardScheduleEntry!]! @cacheControl(inheritMaxAge: true) - lastEpoch: Epoch @cacheControl(inheritMaxAge: true) - pendingEpoch: Epoch @cacheControl(inheritMaxAge: true) - activeRewardScheduleEntry: RewardScheduleEntry @cacheControl(inheritMaxAge: true) -} - -type Block { - id: ID! - fromActiveProducer: Boolean! - hash: Bytes! - parentHash: Bytes! - unclesHash: Bytes! - author: Bytes! - stateRoot: Bytes! - transactionsRoot: Bytes! - receiptsRoot: Bytes! - number: BigInt! - gasUsed: BigInt! - gasLimit: BigInt! - timestamp: BigInt! - difficulty: BigInt! - totalDifficulty: BigInt! - size: BigInt -} - -input Block_filter { - fromActiveProducer: Boolean - number_gte: BigInt - number_lte: BigInt - timestamp_lte: BigInt -} - -enum Block_orderBy { - number - timestamp -} - -type Epoch { - id: ID! - finalized: Boolean! - epochNumber: BigInt! - startBlock: Block @cacheControl(inheritMaxAge: true) - endBlock: Block @cacheControl(inheritMaxAge: true) - producerBlocks: BigInt! - allBlocks: BigInt! - producerBlocksRatio: BigDecimal! - producerRewards: [ProducerEpoch!]! @cacheControl(inheritMaxAge: true) -} - -input Epoch_filter { - epochNumber_gte: BigInt - epochNumber_lte: BigInt -} - -type ProducerEpoch { - id: ID! - address: Bytes! - epoch: Epoch! @cacheControl(inheritMaxAge: true) - totalRewards: BigInt! - blocksProduced: BigInt! - blocksProducedRatio: BigDecimal! -} - -type SlotClaim { - id: ID! - slot: Slot! @cacheControl(inheritMaxAge: true) - owner: Bytes! - winningBid: BigInt! - oldBid: BigInt! - startTime: BigInt! - expirationTime: BigInt! - taxRatePerDay: BigDecimal! -} - -type Slot { - id: ID! - owner: Bytes! - delegate: Bytes! - winningBid: BigInt! - oldBid: BigInt! - startTime: BigInt! - expirationTime: BigInt! - taxRatePerDay: BigDecimal! - claims: [SlotClaim!]! @cacheControl(inheritMaxAge: true) -} - -type Staker { - id: ID! - staked: BigInt! - rank: BigInt -} - -input Staker_filter { - rank_gte: BigInt -} - -enum Staker_orderBy { - rank -} - -type Network { - id: ID! - slot0: Slot @cacheControl(inheritMaxAge: true) - slot1: Slot @cacheControl(inheritMaxAge: true) - slot2: Slot @cacheControl(inheritMaxAge: true) - stakers: [Staker!]! @cacheControl(inheritMaxAge: true) - numStakers: BigInt - totalStaked: BigInt! - stakedPercentiles: [BigInt!]! -} - -type Distributor { - id: ID! - currentDistribution: Distribution @cacheControl(inheritMaxAge: true) -} - -type Distribution { - id: ID! - distributor: Distributor! @cacheControl(inheritMaxAge: true) - timestamp: BigInt! - distributionNumber: BigInt! - merkleRoot: Bytes! - metadataURI: String! -} - -type Claim { - id: ID! - timestamp: BigInt! - index: BigInt! - account: Account! @cacheControl(inheritMaxAge: true) - totalEarned: BigInt! - claimed: BigInt! -} - -type Account { - id: ID! - totalClaimed: BigInt! - totalSlashed: BigInt! - claims: [Claim!]! @cacheControl(inheritMaxAge: true) - slashes: [Slash!]! @cacheControl(inheritMaxAge: true) -} - -type Slash { - id: ID! - timestamp: BigInt! - account: Account! @cacheControl(inheritMaxAge: true) - slashed: BigInt! -} - -type Mutation { - watchContract(address: String!, kind: String!, checkpoint: Boolean!, startingBlock: Int): Boolean! -} - -type Subscription { - onEvent: ResultEvent! -} diff --git a/packages/eden-watcher/src/server.ts b/packages/eden-watcher/src/server.ts deleted file mode 100644 index d55266d9..00000000 --- a/packages/eden-watcher/src/server.ts +++ /dev/null @@ -1,42 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import fs from 'fs'; -import path from 'path'; -import 'reflect-metadata'; -import debug from 'debug'; - -import { ServerCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { createResolvers } from './resolvers'; -import { Indexer } from './indexer'; -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from './database'; - -const log = debug('vulcanize:server'); - -export const main = async (): Promise => { - const serverCmd = new ServerCmd(); - await serverCmd.init(Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - serverCmd.config.server, - serverCmd.clients.ethClient, - serverCmd.ethProvider, - serverCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await serverCmd.initIndexer(Indexer, graphWatcher); - - const typeDefs = fs.readFileSync(path.join(__dirname, 'schema.gql')).toString(); - return serverCmd.exec(createResolvers, typeDefs); -}; - -main().then(() => { - log('Starting server...'); -}).catch(err => { - log(err); -}); diff --git a/packages/eden-watcher/test/queries/account.gql b/packages/eden-watcher/test/queries/account.gql deleted file mode 100644 index 697f66db..00000000 --- a/packages/eden-watcher/test/queries/account.gql +++ /dev/null @@ -1,13 +0,0 @@ -query account($id: String!, $block: Block_height){ - account(id: $id, block: $block){ - id - totalClaimed - totalSlashed - claims{ - id - } - slashes{ - id - } - } -} diff --git a/packages/eden-watcher/test/queries/block.gql b/packages/eden-watcher/test/queries/block.gql deleted file mode 100644 index ab1c9ae4..00000000 --- a/packages/eden-watcher/test/queries/block.gql +++ /dev/null @@ -1,20 +0,0 @@ -query block($id: String!, $block: Block_height){ - block(id: $id, block: $block){ - id - fromActiveProducer - hash - parentHash - unclesHash - author - stateRoot - transactionsRoot - receiptsRoot - number - gasUsed - gasLimit - timestamp - difficulty - totalDifficulty - size - } -} diff --git a/packages/eden-watcher/test/queries/claim.gql b/packages/eden-watcher/test/queries/claim.gql deleted file mode 100644 index cdd67794..00000000 --- a/packages/eden-watcher/test/queries/claim.gql +++ /dev/null @@ -1,12 +0,0 @@ -query claim($id: String!, $block: Block_height){ - claim(id: $id, block: $block){ - id - timestamp - index - account{ - id - } - totalEarned - claimed - } -} diff --git a/packages/eden-watcher/test/queries/distribution.gql b/packages/eden-watcher/test/queries/distribution.gql deleted file mode 100644 index b838cca2..00000000 --- a/packages/eden-watcher/test/queries/distribution.gql +++ /dev/null @@ -1,12 +0,0 @@ -query distribution($id: String!, $block: Block_height){ - distribution(id: $id, block: $block){ - id - distributor{ - id - } - timestamp - distributionNumber - merkleRoot - metadataURI - } -} diff --git a/packages/eden-watcher/test/queries/distributor.gql b/packages/eden-watcher/test/queries/distributor.gql deleted file mode 100644 index dfeeb6fc..00000000 --- a/packages/eden-watcher/test/queries/distributor.gql +++ /dev/null @@ -1,8 +0,0 @@ -query distributor($id: String!, $block: Block_height){ - distributor(id: $id, block: $block){ - id - currentDistribution{ - id - } - } -} diff --git a/packages/eden-watcher/test/queries/epoch.gql b/packages/eden-watcher/test/queries/epoch.gql deleted file mode 100644 index 63ffd458..00000000 --- a/packages/eden-watcher/test/queries/epoch.gql +++ /dev/null @@ -1,19 +0,0 @@ -query epoch($id: String!, $block: Block_height){ - epoch(id: $id, block: $block){ - id - finalized - epochNumber - startBlock{ - id - } - endBlock{ - id - } - producerBlocks - allBlocks - producerBlocksRatio - producerRewards{ - id - } - } -} diff --git a/packages/eden-watcher/test/queries/network.gql b/packages/eden-watcher/test/queries/network.gql deleted file mode 100644 index 19a287d6..00000000 --- a/packages/eden-watcher/test/queries/network.gql +++ /dev/null @@ -1,20 +0,0 @@ -query network($id: String!, $block: Block_height){ - network(id: $id, block: $block){ - id - slot0{ - id - } - slot1{ - id - } - slot2{ - id - } - stakers{ - id - } - numStakers - totalStaked - stakedPercentiles - } -} diff --git a/packages/eden-watcher/test/queries/producer.gql b/packages/eden-watcher/test/queries/producer.gql deleted file mode 100644 index 47fbe7ee..00000000 --- a/packages/eden-watcher/test/queries/producer.gql +++ /dev/null @@ -1,10 +0,0 @@ -query producer($id: String!, $block: Block_height){ - producer(id: $id, block: $block){ - id - active - rewardCollector - rewards - confirmedBlocks - pendingEpochBlocks - } -} diff --git a/packages/eden-watcher/test/queries/producerEpoch.gql b/packages/eden-watcher/test/queries/producerEpoch.gql deleted file mode 100644 index 83d21988..00000000 --- a/packages/eden-watcher/test/queries/producerEpoch.gql +++ /dev/null @@ -1,12 +0,0 @@ -query producerEpoch($id: String!, $block: Block_height){ - producerEpoch(id: $id, block: $block){ - id - address - epoch{ - id - } - totalRewards - blocksProduced - blocksProducedRatio - } -} diff --git a/packages/eden-watcher/test/queries/producerRewardCollectorChange.gql b/packages/eden-watcher/test/queries/producerRewardCollectorChange.gql deleted file mode 100644 index 249c419c..00000000 --- a/packages/eden-watcher/test/queries/producerRewardCollectorChange.gql +++ /dev/null @@ -1,8 +0,0 @@ -query producerRewardCollectorChange($id: String!, $block: Block_height){ - producerRewardCollectorChange(id: $id, block: $block){ - id - blockNumber - producer - rewardCollector - } -} diff --git a/packages/eden-watcher/test/queries/producerSet.gql b/packages/eden-watcher/test/queries/producerSet.gql deleted file mode 100644 index 6ca0e145..00000000 --- a/packages/eden-watcher/test/queries/producerSet.gql +++ /dev/null @@ -1,8 +0,0 @@ -query producerSet($id: String!, $block: Block_height){ - producerSet(id: $id, block: $block){ - id - producers{ - id - } - } -} diff --git a/packages/eden-watcher/test/queries/producerSetChange.gql b/packages/eden-watcher/test/queries/producerSetChange.gql deleted file mode 100644 index 2e79f638..00000000 --- a/packages/eden-watcher/test/queries/producerSetChange.gql +++ /dev/null @@ -1,8 +0,0 @@ -query producerSetChange($id: String!, $block: Block_height){ - producerSetChange(id: $id, block: $block){ - id - blockNumber - producer - changeType - } -} diff --git a/packages/eden-watcher/test/queries/rewardSchedule.gql b/packages/eden-watcher/test/queries/rewardSchedule.gql deleted file mode 100644 index 0d69aeb0..00000000 --- a/packages/eden-watcher/test/queries/rewardSchedule.gql +++ /dev/null @@ -1,17 +0,0 @@ -query rewardSchedule($id: String!, $block: Block_height){ - rewardSchedule(id: $id, block: $block){ - id - rewardScheduleEntries{ - id - } - lastEpoch{ - id - } - pendingEpoch{ - id - } - activeRewardScheduleEntry{ - id - } - } -} diff --git a/packages/eden-watcher/test/queries/rewardScheduleEntry.gql b/packages/eden-watcher/test/queries/rewardScheduleEntry.gql deleted file mode 100644 index ecf4aee2..00000000 --- a/packages/eden-watcher/test/queries/rewardScheduleEntry.gql +++ /dev/null @@ -1,8 +0,0 @@ -query rewardScheduleEntry($id: String!, $block: Block_height){ - rewardScheduleEntry(id: $id, block: $block){ - id - startTime - epochDuration - rewardsPerEpoch - } -} diff --git a/packages/eden-watcher/test/queries/slash.gql b/packages/eden-watcher/test/queries/slash.gql deleted file mode 100644 index db0c611c..00000000 --- a/packages/eden-watcher/test/queries/slash.gql +++ /dev/null @@ -1,10 +0,0 @@ -query slash($id: String!, $block: Block_height){ - slash(id: $id, block: $block){ - id - timestamp - account{ - id - } - slashed - } -} diff --git a/packages/eden-watcher/test/queries/slot.gql b/packages/eden-watcher/test/queries/slot.gql deleted file mode 100644 index f570f03b..00000000 --- a/packages/eden-watcher/test/queries/slot.gql +++ /dev/null @@ -1,15 +0,0 @@ -query slot($id: String!, $block: Block_height){ - slot(id: $id, block: $block){ - id - owner - delegate - winningBid - oldBid - startTime - expirationTime - taxRatePerDay - claims{ - id - } - } -} diff --git a/packages/eden-watcher/test/queries/slotClaim.gql b/packages/eden-watcher/test/queries/slotClaim.gql deleted file mode 100644 index 425664df..00000000 --- a/packages/eden-watcher/test/queries/slotClaim.gql +++ /dev/null @@ -1,14 +0,0 @@ -query slotClaim($id: String!, $block: Block_height){ - slotClaim(id: $id, block: $block){ - id - slot{ - id - } - owner - winningBid - oldBid - startTime - expirationTime - taxRatePerDay - } -} diff --git a/packages/eden-watcher/test/queries/staker.gql b/packages/eden-watcher/test/queries/staker.gql deleted file mode 100644 index bb4cdd51..00000000 --- a/packages/eden-watcher/test/queries/staker.gql +++ /dev/null @@ -1,7 +0,0 @@ -query staker($id: String!, $block: Block_height){ - staker(id: $id, block: $block){ - id - staked - rank - } -} diff --git a/packages/eden-watcher/tsconfig.json b/packages/eden-watcher/tsconfig.json deleted file mode 100644 index 4e55bfd1..00000000 --- a/packages/eden-watcher/tsconfig.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "compilerOptions": { - /* Visit https://aka.ms/tsconfig.json to read more about this file */ - - /* Basic Options */ - // "incremental": true, /* Enable incremental compilation */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ - "lib": ["es2019"], /* Specify library files to be included in the compilation. */ - // "allowJs": true, /* Allow javascript files to be compiled. */ - // "checkJs": true, /* Report errors in .js files. */ - // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ - // "declaration": true, /* Generates corresponding '.d.ts' file. */ - // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - "sourceMap": true, /* Generates corresponding '.map' file. */ - // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "dist", /* Redirect output structure to the directory. */ - // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - // "composite": true, /* Enable project compilation */ - // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ - // "removeComments": true, /* Do not emit comments to output. */ - // "noEmit": true, /* Do not emit outputs. */ - // "importHelpers": true, /* Import emit helpers from 'tslib'. */ - "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ - // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* Enable strict null checks. */ - // "strictFunctionTypes": true, /* Enable strict checking of function types. */ - // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ - // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ - // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - - /* Additional Checks */ - // "noUnusedLocals": true, /* Report errors on unused locals. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ - - /* Module Resolution Options */ - // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ - // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ - // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ - // "typeRoots": [], /* List of folders to include type definitions from. */ - // "types": [], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ - // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - - /* Source Map Options */ - // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ - // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - - /* Experimental Options */ - "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ - // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - - /* Advanced Options */ - "skipLibCheck": true, /* Skip type checking of declaration files. */ - "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ - "resolveJsonModule": true /* Enabling the option allows importing JSON, and validating the types in that JSON file. */ - }, - "include": ["src/**/*"] -} diff --git a/packages/erc20-watcher/.eslintignore b/packages/erc20-watcher/.eslintignore deleted file mode 100644 index 653874b5..00000000 --- a/packages/erc20-watcher/.eslintignore +++ /dev/null @@ -1,5 +0,0 @@ -# Don't lint node_modules. -node_modules - -# Don't lint build output. -dist diff --git a/packages/erc20-watcher/.eslintrc.json b/packages/erc20-watcher/.eslintrc.json deleted file mode 100644 index a2b842c2..00000000 --- a/packages/erc20-watcher/.eslintrc.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "env": { - "browser": true, - "es2021": true - }, - "extends": [ - "semistandard", - "plugin:@typescript-eslint/recommended" - ], - "parser": "@typescript-eslint/parser", - "parserOptions": { - "ecmaVersion": 12, - "sourceType": "module" - }, - "plugins": [ - "@typescript-eslint" - ], - "rules": { - "indent": ["error", 2, { "SwitchCase": 1 }], - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/explicit-module-boundary-types": [ - "warn", - { - "allowArgumentsExplicitlyTypedAsAny": true - } - ] - } -} diff --git a/packages/erc20-watcher/.gitignore b/packages/erc20-watcher/.gitignore deleted file mode 100644 index 3ac0fb0a..00000000 --- a/packages/erc20-watcher/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -.idea/ -.vscode/ -node_modules/ -build/ -tmp/ -temp/ - -#Hardhat files -cache -artifacts diff --git a/packages/erc20-watcher/README.md b/packages/erc20-watcher/README.md deleted file mode 100644 index 309006b6..00000000 --- a/packages/erc20-watcher/README.md +++ /dev/null @@ -1,198 +0,0 @@ -# ERC20 Watcher - -First try the [erc20 demo in stack orchestrator](https://github.com/cerc-io/stack-orchestrator/tree/main/app/data/stacks/erc20) to quickly get started. Advanced users can see [here](/docs/README.md) for instructions on setting up a local environment by hand. - -## Build - -Build files: - -```bash -yarn build -``` - -## Run - -Start the job runner: - -```bash -yarn job-runner -``` - -For development or to specify the config file: -```bash - yarn job-runner:dev - yarn job-runner -f environments/local.toml -``` - -Then, Start the server: - -```bash -yarn server -``` - -For development or to specify the config file: -```bash -yarn server:dev -yarn server -f environments/local.toml -``` - -See the GQL console at: http://localhost:3001/graphql -Note: the port may be different depending on your configuration. - -Deploy an ERC20 token: - -```bash -yarn token:deploy -``` -In the output you'll see: - -```bash -GLD Token deployed to: 0xTokenAddress -``` - -Export the address of the deployed token to a shell variable for later use: - -```bash -export TOKEN_ADDRESS=0xTokenAddress -``` - -Get the main account address: -```bash -yarn account -``` - -and export it as well: - -```bash -export PRIMARY_ACCOUNT=0xPrimaryAccount -``` - -Run the following command to watch the contract: - -```bash -yarn watch:contract --address $TOKEN_ADDRESS --kind ERC20 --checkpoint false -``` - -For specifying a config file: -```bash -yarn watch:contract -f environments/local.toml --address 0xTokenAddress --kind ERC20 --checkpoint false -``` - -To fill a block range: - -```bash -yarn fill --startBlock --endBlock -``` - -To get the current block hash at any time, run: - -```bash -yarn block:latest -``` - -Add a new account to Metamask and export the account address to a shell variable for later use: - -```bash -export RECIPIENT_ADDRESS=0xRecipientAddress -``` - -Run the following GQL query against the [http://127.0.0.1:3001/graphql](http://127.0.0.1:3001/graphql) to get the name, symbol and total supply of the deployed token: - -```graphql -query { - name( - blockHash: "LATEST_BLOCK_HASH" - token: "0xTokenAddress" - ) { - value - proof { - data - } - } - - symbol( - blockHash: "LATEST_BLOCK_HASH" - token: "0xTokenAddress" - ) { - value - proof { - data - } - } - - totalSupply( - blockHash: "LATEST_BLOCK_HASH" - token: "0xTokenAddress" - ) { - value - proof { - data - } - } -} -``` - -Run the following GQL query to get balances for the main and the recipient account at the latest block hash: - -```graphql -query { - fromBalanceOf: balanceOf( - blockHash: "LATEST_BLOCK_HASH" - token: "0xTokenAddress", - # main/primary account having all the balance initially - owner: "0xPrimaryAccount" - ) { - value - proof { - data - } - } - toBalanceOf: balanceOf( - blockHash: "LATEST_BLOCK_HASH" - token: "0xTokenAddress", - owner: "0xRecipientAddress" - ) { - value - proof { - data - } - } -} -``` - -Run the following GQL subscription at the GraphQL endpoint: - -```graphql -subscription { - onEvent { - blockHash - contract - event { - __typename - ... on TransferEvent { - from - to - value - }, - ... on ApprovalEvent { - owner - spender - value - } - } - proof { - data - } - } -} -``` - -Transfer tokens to the recipient account: - -```bash -yarn token:transfer --token $TOKEN_ADDRESS --to $RECIPIENT_ADDRESS --amount 100 -``` - -A Transfer event to the `RECIPIENT_ADDRESS` should be visible in the subscription. - -Get the latest block hash again, then fire the GQL query above to get updated balances for the main (from) and the recipient (to) account. diff --git a/packages/erc20-watcher/environments/local.toml b/packages/erc20-watcher/environments/local.toml deleted file mode 100644 index ce089b5b..00000000 --- a/packages/erc20-watcher/environments/local.toml +++ /dev/null @@ -1,40 +0,0 @@ -[server] - host = "127.0.0.1" - port = 3001 - mode = "eth_call" - kind = "active" - -[metrics] - host = "127.0.0.1" - port = 9000 - [metrics.gql] - port = 9001 - -[database] - type = "postgres" - host = "localhost" - port = 5432 - database = "erc20-watcher" - username = "postgres" - password = "postgres" - synchronize = true - logging = false - -[upstream] - [upstream.ethServer] - gqlApiEndpoint = "http://127.0.0.1:8082/graphql" - rpcProviderEndpoint = "http://127.0.0.1:8081" - - [upstream.cache] - name = "requests" - enabled = false - deleteOnStart = false - -[jobQueue] - dbConnectionString = "postgres://postgres:postgres@localhost/erc20-watcher-job-queue" - maxCompletionLagInSecs = 300 - jobDelayInMilliSecs = 100 - eventsInBatch = 50 - blockDelayInMilliSecs = 2000 - prefetchBlocksInMem = true - prefetchBlockCount = 10 diff --git a/packages/erc20-watcher/hardhat.config.ts b/packages/erc20-watcher/hardhat.config.ts deleted file mode 100644 index d9ea112e..00000000 --- a/packages/erc20-watcher/hardhat.config.ts +++ /dev/null @@ -1,30 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import '@nomiclabs/hardhat-waffle'; - -import './test/tasks/token-deploy'; -import './test/tasks/token-transfer'; -import './test/tasks/token-approve'; -import './test/tasks/token-transfer-from'; -import './test/tasks/block-latest'; -import './test/tasks/account'; - -// You need to export an object to set up your config -// Go to https://hardhat.org/config/ to learn more - -/** - * @type import('hardhat/config').HardhatUserConfig - */ -export default { - solidity: '0.8.0', - networks: { - docker: { - url: process.env.ETH_RPC_URL - } - }, - paths: { - sources: './test/contracts' - } -}; diff --git a/packages/erc20-watcher/package.json b/packages/erc20-watcher/package.json deleted file mode 100644 index 2c5fb855..00000000 --- a/packages/erc20-watcher/package.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "name": "@cerc-io/erc20-watcher", - "version": "0.2.38", - "description": "ERC20 Watcher", - "private": true, - "main": "dist/index.js", - "scripts": { - "lint": "eslint .", - "build": "tsc", - "server": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true node --enable-source-maps dist/server.js", - "server:dev": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true ts-node src/server.ts", - "job-runner": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true node --enable-source-maps dist/job-runner.js", - "job-runner:dev": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true ts-node src/job-runner.ts", - "watch:contract": "node --enable-source-maps dist/cli/watch-contract.js", - "watch:contract:dev": "ts-node src/cli/watch-contract.ts", - "fill": "DEBUG=vulcanize:* node dist/fill.js", - "fill:dev": "DEBUG=vulcanize:* ts-node src/fill.ts", - "token:deploy": "hardhat --network localhost token-deploy", - "token:deploy:docker": "hardhat --network docker token-deploy", - "token:transfer": "hardhat --network localhost token-transfer", - "token:transfer:docker": "hardhat --network docker token-transfer", - "token:approve": "hardhat --network localhost token-approve", - "token:approve:docker": "hardhat --network docker token-approve", - "token:transfer-from": "hardhat --network localhost token-transfer-from", - "token:transfer-from:docker": "hardhat --network docker token-transfer-from", - "block:latest": "hardhat --network localhost block-latest", - "block:latest:docker": "hardhat --network docker block-latest", - "account": "hardhat --network localhost account", - "account:docker": "hardhat --network docker account", - "reset": "DEBUG=vulcanize:* node --enable-source-maps dist/cli/reset.js", - "reset:dev": "DEBUG=vulcanize:* ts-node src/cli/reset.ts" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/cerc-io/watcher-ts.git" - }, - "author": "", - "license": "AGPL-3.0", - "bugs": { - "url": "https://github.com/cerc-io/watcher-ts/issues" - }, - "homepage": "https://github.com/cerc-io/watcher-ts#readme", - "dependencies": { - "@apollo/client": "^3.3.19", - "@cerc-io/cli": "^0.2.38", - "@cerc-io/ipld-eth-client": "^0.2.38", - "@cerc-io/solidity-mapper": "^0.2.38", - "@cerc-io/util": "^0.2.38", - "@ethersproject/providers": "^5.4.4", - "apollo-type-bigint": "^0.1.3", - "debug": "^4.3.1", - "ethers": "^5.4.4", - "graphql": "^15.5.0", - "graphql-request": "^3.4.0", - "json-bigint": "^1.0.0", - "reflect-metadata": "^0.1.13", - "typeorm": "^0.2.32" - }, - "devDependencies": { - "@ethersproject/abi": "^5.3.0", - "@nomiclabs/hardhat-ethers": "^2.0.2", - "@nomiclabs/hardhat-waffle": "^2.0.1", - "@openzeppelin/contracts": "^4.3.2", - "@types/json-bigint": "^1.0.0", - "@typescript-eslint/eslint-plugin": "^5.47.1", - "@typescript-eslint/parser": "^5.47.1", - "eslint": "^8.35.0", - "eslint-config-semistandard": "^15.0.1", - "eslint-config-standard": "^16.0.3", - "eslint-plugin-import": "^2.27.5", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-promise": "^5.1.0", - "eslint-plugin-standard": "^5.0.0", - "hardhat": "^2.3.0", - "nodemon": "^2.0.7", - "ts-node": "^10.2.1" - } -} diff --git a/packages/erc20-watcher/src/artifacts/ERC20.json b/packages/erc20-watcher/src/artifacts/ERC20.json deleted file mode 100644 index 26308b70..00000000 --- a/packages/erc20-watcher/src/artifacts/ERC20.json +++ /dev/null @@ -1,365 +0,0 @@ -{ - "abi": [ - { - "inputs": [ - { - "internalType": "string", - "name": "name_", - "type": "string" - }, - { - "internalType": "string", - "name": "symbol_", - "type": "string" - } - ], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "spender", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "value", - "type": "uint256" - } - ], - "name": "Approval", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "from", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "value", - "type": "uint256" - } - ], - "name": "Transfer", - "type": "event" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "internalType": "address", - "name": "spender", - "type": "address" - } - ], - "name": "allowance", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "spender", - "type": "address" - }, - { - "internalType": "uint256", - "name": "amount", - "type": "uint256" - } - ], - "name": "approve", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "balanceOf", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "decimals", - "outputs": [ - { - "internalType": "uint8", - "name": "", - "type": "uint8" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "spender", - "type": "address" - }, - { - "internalType": "uint256", - "name": "subtractedValue", - "type": "uint256" - } - ], - "name": "decreaseAllowance", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "spender", - "type": "address" - }, - { - "internalType": "uint256", - "name": "addedValue", - "type": "uint256" - } - ], - "name": "increaseAllowance", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "name", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "symbol", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "totalSupply", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "recipient", - "type": "address" - }, - { - "internalType": "uint256", - "name": "amount", - "type": "uint256" - } - ], - "name": "transfer", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "sender", - "type": "address" - }, - { - "internalType": "address", - "name": "recipient", - "type": "address" - }, - { - "internalType": "uint256", - "name": "amount", - "type": "uint256" - } - ], - "name": "transferFrom", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - } - ], - "storageLayout": { - "storage": [ - { - "astId": 15, - "contract": "@openzeppelin/contracts/token/ERC20/ERC20.sol:ERC20", - "label": "_balances", - "offset": 0, - "slot": "0", - "type": "t_mapping(t_address,t_uint256)" - }, - { - "astId": 21, - "contract": "@openzeppelin/contracts/token/ERC20/ERC20.sol:ERC20", - "label": "_allowances", - "offset": 0, - "slot": "1", - "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))" - }, - { - "astId": 23, - "contract": "@openzeppelin/contracts/token/ERC20/ERC20.sol:ERC20", - "label": "_totalSupply", - "offset": 0, - "slot": "2", - "type": "t_uint256" - }, - { - "astId": 25, - "contract": "@openzeppelin/contracts/token/ERC20/ERC20.sol:ERC20", - "label": "_name", - "offset": 0, - "slot": "3", - "type": "t_string_storage" - }, - { - "astId": 27, - "contract": "@openzeppelin/contracts/token/ERC20/ERC20.sol:ERC20", - "label": "_symbol", - "offset": 0, - "slot": "4", - "type": "t_string_storage" - } - ], - "types": { - "t_address": { - "encoding": "inplace", - "label": "address", - "numberOfBytes": "20" - }, - "t_mapping(t_address,t_mapping(t_address,t_uint256))": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => mapping(address => uint256))", - "numberOfBytes": "32", - "value": "t_mapping(t_address,t_uint256)" - }, - "t_mapping(t_address,t_uint256)": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => uint256)", - "numberOfBytes": "32", - "value": "t_uint256" - }, - "t_string_storage": { - "encoding": "bytes", - "label": "string", - "numberOfBytes": "32" - }, - "t_uint256": { - "encoding": "inplace", - "label": "uint256", - "numberOfBytes": "32" - } - } - } -} \ No newline at end of file diff --git a/packages/erc20-watcher/src/artifacts/ERC20NameBytes.json b/packages/erc20-watcher/src/artifacts/ERC20NameBytes.json deleted file mode 100644 index 2d3c877a..00000000 --- a/packages/erc20-watcher/src/artifacts/ERC20NameBytes.json +++ /dev/null @@ -1,17 +0,0 @@ -[ - { - "constant": true, - "inputs": [], - "name": "name", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - } -] diff --git a/packages/erc20-watcher/src/artifacts/ERC20SymbolBytes.json b/packages/erc20-watcher/src/artifacts/ERC20SymbolBytes.json deleted file mode 100644 index a76d6163..00000000 --- a/packages/erc20-watcher/src/artifacts/ERC20SymbolBytes.json +++ /dev/null @@ -1,17 +0,0 @@ -[ - { - "constant": true, - "inputs": [], - "name": "symbol", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - } -] diff --git a/packages/erc20-watcher/src/cli/reset-cmds/job-queue.ts b/packages/erc20-watcher/src/cli/reset-cmds/job-queue.ts deleted file mode 100644 index c33cbfd6..00000000 --- a/packages/erc20-watcher/src/cli/reset-cmds/job-queue.ts +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import debug from 'debug'; - -import { getConfig, resetJobs, Config } from '@cerc-io/util'; - -const log = debug('vulcanize:reset-job-queue'); - -export const command = 'job-queue'; - -export const desc = 'Reset job queue'; - -export const builder = {}; - -export const handler = async (argv: any): Promise => { - const config: Config = await getConfig(argv.configFile); - await resetJobs(config); - - log('Job queue reset successfully'); -}; diff --git a/packages/erc20-watcher/src/cli/reset-cmds/state.ts b/packages/erc20-watcher/src/cli/reset-cmds/state.ts deleted file mode 100644 index 33211d6e..00000000 --- a/packages/erc20-watcher/src/cli/reset-cmds/state.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { ResetStateCmd } from '@cerc-io/cli'; - -import { Database } from '../../database'; - -export const command = 'state'; - -export const desc = 'Reset State to a given block number'; - -export const builder = { - blockNumber: { - type: 'number' - } -}; - -export const handler = async (argv: any): Promise => { - const resetStateCmd = new ResetStateCmd(); - await resetStateCmd.init(argv, Database); - - await resetStateCmd.exec(); -}; diff --git a/packages/erc20-watcher/src/cli/reset-cmds/watcher.ts b/packages/erc20-watcher/src/cli/reset-cmds/watcher.ts deleted file mode 100644 index c6e651f5..00000000 --- a/packages/erc20-watcher/src/cli/reset-cmds/watcher.ts +++ /dev/null @@ -1,26 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { ResetWatcherCmd } from '@cerc-io/cli'; - -import { Database } from '../../database'; -import { Indexer } from '../../indexer'; - -export const command = 'watcher'; - -export const desc = 'Reset watcher to a block number'; - -export const builder = { - blockNumber: { - type: 'number' - } -}; - -export const handler = async (argv: any): Promise => { - const resetWatcherCmd = new ResetWatcherCmd(); - await resetWatcherCmd.init(argv, Database); - await resetWatcherCmd.initIndexer(Indexer); - - await resetWatcherCmd.exec(); -}; diff --git a/packages/erc20-watcher/src/cli/reset.ts b/packages/erc20-watcher/src/cli/reset.ts deleted file mode 100644 index 95648c88..00000000 --- a/packages/erc20-watcher/src/cli/reset.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { getResetYargs } from '@cerc-io/util'; - -const log = debug('vulcanize:reset'); - -const main = async () => { - return getResetYargs() - .commandDir('reset-cmds', { extensions: ['ts', 'js'], exclude: /([a-zA-Z0-9\s_\\.\-:])+(.d.ts)$/ }) - .demandCommand(1) - .help() - .argv; -}; - -main().then(() => { - process.exit(); -}).catch(err => { - log(err); -}); diff --git a/packages/erc20-watcher/src/cli/watch-contract.ts b/packages/erc20-watcher/src/cli/watch-contract.ts deleted file mode 100644 index b68568e7..00000000 --- a/packages/erc20-watcher/src/cli/watch-contract.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { WatchContractCmd } from '@cerc-io/cli'; - -import { Database } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:watch-contract'); - -const main = async (): Promise => { - const watchContractCmd = new WatchContractCmd(); - await watchContractCmd.init(Database); - await watchContractCmd.initIndexer(Indexer); - - await watchContractCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/erc20-watcher/src/client.ts b/packages/erc20-watcher/src/client.ts deleted file mode 100644 index 5dca1c57..00000000 --- a/packages/erc20-watcher/src/client.ts +++ /dev/null @@ -1,55 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { gql } from '@apollo/client/core'; -import { GraphQLClient, GraphQLConfig } from '@cerc-io/ipld-eth-client'; - -import { queryName, queryDecimals, queryTotalSupply, querySymbol } from './queries'; - -export class Client { - _config: GraphQLConfig; - _client: GraphQLClient; - - constructor (config: GraphQLConfig) { - this._config = config; - - this._client = new GraphQLClient(config); - } - - async getSymbol (blockHash: string, token: string): Promise { - const { symbol } = await this._client.query( - gql(querySymbol), - { blockHash, token } - ); - - return symbol; - } - - async getName (blockHash: string, token: string): Promise { - const { name } = await this._client.query( - gql(queryName), - { blockHash, token } - ); - - return name; - } - - async getTotalSupply (blockHash: string, token: string): Promise { - const { totalSupply } = await this._client.query( - gql(queryTotalSupply), - { blockHash, token } - ); - - return totalSupply; - } - - async getDecimals (blockHash: string, token: string): Promise { - const { decimals } = await this._client.query( - gql(queryDecimals), - { blockHash, token } - ); - - return decimals; - } -} diff --git a/packages/erc20-watcher/src/database.ts b/packages/erc20-watcher/src/database.ts deleted file mode 100644 index fd95b530..00000000 --- a/packages/erc20-watcher/src/database.ts +++ /dev/null @@ -1,282 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import { Connection, ConnectionOptions, DeepPartial, EntityTarget, FindConditions, FindManyOptions, QueryRunner } from 'typeorm'; -import path from 'path'; - -import { Database as BaseDatabase, DatabaseInterface, QueryOptions, StateKind, Where } from '@cerc-io/util'; - -import { Allowance } from './entity/Allowance'; -import { Balance } from './entity/Balance'; -import { Contract } from './entity/Contract'; -import { Event } from './entity/Event'; -import { SyncStatus } from './entity/SyncStatus'; -import { BlockProgress } from './entity/BlockProgress'; -import { State } from './entity/State'; -import { StateSyncStatus } from './entity/StateSyncStatus'; - -export const ENTITIES = [Allowance, Balance]; - -export class Database implements DatabaseInterface { - _config: ConnectionOptions; - _conn!: Connection; - _baseDatabase: BaseDatabase; - - constructor (config: ConnectionOptions) { - assert(config); - - this._config = { - ...config, - entities: [path.join(__dirname, 'entity/*')] - }; - - this._baseDatabase = new BaseDatabase(this._config); - } - - get baseDatabase (): BaseDatabase { - return this._baseDatabase; - } - - async init (): Promise { - this._conn = await this._baseDatabase.init(); - } - - async close (): Promise { - return this._baseDatabase.close(); - } - - getNewState (): State { - return new State(); - } - - async getStates (where: FindConditions): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getStates(repo, where); - } - - async getLatestState (contractAddress: string, kind: StateKind | null, blockNumber?: number): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getLatestState(repo, contractAddress, kind, blockNumber); - } - - async getPrevState (blockHash: string, contractAddress: string, kind?: string): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getPrevState(repo, blockHash, contractAddress, kind); - } - - // Fetch all diff States after the specified block number. - async getDiffStatesInRange (contractAddress: string, startblock: number, endBlock: number): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getDiffStatesInRange(repo, contractAddress, startblock, endBlock); - } - - async saveOrUpdateState (dbTx: QueryRunner, state: State): Promise { - const repo = dbTx.manager.getRepository(State); - - return this._baseDatabase.saveOrUpdateState(repo, state); - } - - async removeStates (dbTx: QueryRunner, blockNumber: number, kind: string): Promise { - const repo = dbTx.manager.getRepository(State); - - await this._baseDatabase.removeStates(repo, blockNumber, kind); - } - - async removeStatesAfterBlock (dbTx: QueryRunner, blockNumber: number): Promise { - const repo = dbTx.manager.getRepository(State); - - await this._baseDatabase.removeStatesAfterBlock(repo, blockNumber); - } - - async getStateSyncStatus (): Promise { - const repo = this._conn.getRepository(StateSyncStatus); - - return this._baseDatabase.getStateSyncStatus(repo); - } - - async updateStateSyncStatusIndexedBlock (queryRunner: QueryRunner, blockNumber: number, force?: boolean): Promise { - const repo = queryRunner.manager.getRepository(StateSyncStatus); - - return this._baseDatabase.updateStateSyncStatusIndexedBlock(repo, blockNumber, force); - } - - async updateStateSyncStatusCheckpointBlock (queryRunner: QueryRunner, blockNumber: number, force?: boolean): Promise { - const repo = queryRunner.manager.getRepository(StateSyncStatus); - - return this._baseDatabase.updateStateSyncStatusCheckpointBlock(repo, blockNumber, force); - } - - async getBalance ({ blockHash, token, owner }: { blockHash: string, token: string, owner: string }): Promise { - return this._conn.getRepository(Balance) - .createQueryBuilder('balance') - .where('block_hash = :blockHash AND token = :token AND owner = :owner', { - blockHash, - token, - owner - }) - .getOne(); - } - - async getAllowance ({ blockHash, token, owner, spender }: { blockHash: string, token: string, owner: string, spender: string }): Promise { - return this._conn.getRepository(Allowance) - .createQueryBuilder('allowance') - .where('block_hash = :blockHash AND token = :token AND owner = :owner AND spender = :spender', { - blockHash, - token, - owner, - spender - }) - .getOne(); - } - - async saveBalance ({ blockHash, blockNumber, token, owner, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(Balance); - const entity = repo.create({ blockHash, blockNumber, token, owner, value, proof }); - return repo.save(entity); - } - - async saveAllowance ({ blockHash, blockNumber, token, owner, spender, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(Allowance); - const entity = repo.create({ blockHash, blockNumber, token, owner, spender, value, proof }); - return repo.save(entity); - } - - async getContracts (): Promise { - const repo = this._conn.getRepository(Contract); - - return this._baseDatabase.getContracts(repo); - } - - async createTransactionRunner (): Promise { - return this._baseDatabase.createTransactionRunner(); - } - - async getProcessedBlockCountForRange (fromBlockNumber: number, toBlockNumber: number): Promise<{ expected: number, actual: number }> { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getProcessedBlockCountForRange(repo, fromBlockNumber, toBlockNumber); - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise> { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getEventsInRange(repo, fromBlockNumber, toBlockNumber); - } - - async saveEventEntity (queryRunner: QueryRunner, entity: Event): Promise { - const repo = queryRunner.manager.getRepository(Event); - return this._baseDatabase.saveEventEntity(repo, entity); - } - - async getBlockEvents (blockHash: string, where: Where, queryOptions: QueryOptions): Promise { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getBlockEvents(repo, blockHash, where, queryOptions); - } - - async saveBlockWithEvents (queryRunner: QueryRunner, block: DeepPartial, events: DeepPartial[]): Promise { - const blockRepo = queryRunner.manager.getRepository(BlockProgress); - const eventRepo = queryRunner.manager.getRepository(Event); - - return this._baseDatabase.saveBlockWithEvents(blockRepo, eventRepo, block, events); - } - - async saveEvents (queryRunner: QueryRunner, events: Event[]): Promise { - const eventRepo = queryRunner.manager.getRepository(Event); - - return this._baseDatabase.saveEvents(eventRepo, events); - } - - async saveContract (queryRunner: QueryRunner, address: string, kind: string, checkpoint: boolean, startingBlock: number): Promise { - const repo = queryRunner.manager.getRepository(Contract); - - return this._baseDatabase.saveContract(repo, address, kind, checkpoint, startingBlock); - } - - async updateSyncStatusIndexedBlock (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusIndexedBlock(repo, blockHash, blockNumber, force); - } - - async updateSyncStatusCanonicalBlock (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusCanonicalBlock(repo, blockHash, blockNumber, force); - } - - async updateSyncStatusChainHead (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusChainHead(repo, blockHash, blockNumber, force); - } - - async getSyncStatus (queryRunner: QueryRunner): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.getSyncStatus(repo); - } - - async getEvent (id: string): Promise { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getEvent(repo, id); - } - - async getBlocksAtHeight (height: number, isPruned: boolean): Promise { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getBlocksAtHeight(repo, height, isPruned); - } - - async markBlocksAsPruned (queryRunner: QueryRunner, blocks: BlockProgress[]): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.markBlocksAsPruned(repo, blocks); - } - - async getBlockProgress (blockHash: string): Promise { - const repo = this._conn.getRepository(BlockProgress); - return this._baseDatabase.getBlockProgress(repo, blockHash); - } - - async getBlockProgressEntities (where: FindConditions, options: FindManyOptions): Promise { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getBlockProgressEntities(repo, where, options); - } - - async getEntitiesForBlock (blockHash: string, tableName: string): Promise { - return this._baseDatabase.getEntitiesForBlock(blockHash, tableName); - } - - async saveBlockProgress (queryRunner: QueryRunner, block: DeepPartial): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.saveBlockProgress(repo, block); - } - - async updateBlockProgress (queryRunner: QueryRunner, block: BlockProgress, lastProcessedEventIndex: number): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.updateBlockProgress(repo, block, lastProcessedEventIndex); - } - - async removeEntities (queryRunner: QueryRunner, entity: new () => Entity, findConditions?: FindManyOptions | FindConditions): Promise { - return this._baseDatabase.removeEntities(queryRunner, entity, findConditions); - } - - async deleteEntitiesByConditions (queryRunner: QueryRunner, entity: EntityTarget, findConditions: FindConditions): Promise { - await this._baseDatabase.deleteEntitiesByConditions(queryRunner, entity, findConditions); - } - - async getAncestorAtDepth (blockHash: string, depth: number): Promise { - return this._baseDatabase.getAncestorAtDepth(blockHash, depth); - } -} diff --git a/packages/erc20-watcher/src/entity/Allowance.ts b/packages/erc20-watcher/src/entity/Allowance.ts deleted file mode 100644 index fee69c64..00000000 --- a/packages/erc20-watcher/src/entity/Allowance.ts +++ /dev/null @@ -1,34 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash', 'blockNumber', 'token', 'owner', 'spender'], { unique: true }) -export class Allowance { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - token!: string; - - @Column('varchar', { length: 42 }) - owner!: string; - - @Column('varchar', { length: 42 }) - spender!: string; - - @Column('numeric', { transformer: bigintTransformer }) - value!: bigint; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/erc20-watcher/src/entity/Balance.ts b/packages/erc20-watcher/src/entity/Balance.ts deleted file mode 100644 index 0668ae3e..00000000 --- a/packages/erc20-watcher/src/entity/Balance.ts +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash', 'blockNumber', 'token', 'owner'], { unique: true }) -export class Balance { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - token!: string; - - @Column('varchar', { length: 42 }) - owner!: string; - - @Column('numeric', { transformer: bigintTransformer }) - value!: bigint; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/erc20-watcher/src/entity/BlockProgress.ts b/packages/erc20-watcher/src/entity/BlockProgress.ts deleted file mode 100644 index 7e918294..00000000 --- a/packages/erc20-watcher/src/entity/BlockProgress.ts +++ /dev/null @@ -1,49 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, CreateDateColumn } from 'typeorm'; - -import { BlockProgressInterface } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash'], { unique: true }) -@Index(['blockNumber']) -@Index(['parentHash']) -export class BlockProgress implements BlockProgressInterface { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar') - cid!: string; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('varchar', { length: 66 }) - parentHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('integer') - blockTimestamp!: number; - - @Column('integer') - numEvents!: number; - - @Column('integer') - numProcessedEvents!: number; - - @Column('integer') - lastProcessedEventIndex!: number; - - @Column('boolean') - isComplete!: boolean; - - @Column('boolean', { default: false }) - isPruned!: boolean; - - @CreateDateColumn() - createdAt!: Date; -} diff --git a/packages/erc20-watcher/src/entity/Contract.ts b/packages/erc20-watcher/src/entity/Contract.ts deleted file mode 100644 index 393e65f0..00000000 --- a/packages/erc20-watcher/src/entity/Contract.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['address'], { unique: true }) -export class Contract { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 42 }) - address!: string; - - @Column('varchar', { length: 8 }) - kind!: string; - - @Column('boolean') - checkpoint!: boolean; - - @Column('integer') - startingBlock!: number; -} diff --git a/packages/erc20-watcher/src/entity/Event.ts b/packages/erc20-watcher/src/entity/Event.ts deleted file mode 100644 index d0ce4f4e..00000000 --- a/packages/erc20-watcher/src/entity/Event.ts +++ /dev/null @@ -1,41 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, ManyToOne } from 'typeorm'; -import { BlockProgress } from './BlockProgress'; - -@Entity() -// Index to query all events for a contract efficiently. -@Index(['block', 'contract']) -// Index to query events by name efficiently. -@Index(['block', 'contract', 'eventName']) -export class Event { - @PrimaryGeneratedColumn() - id!: number; - - @ManyToOne(() => BlockProgress, { onDelete: 'CASCADE' }) - block!: BlockProgress; - - @Column('varchar', { length: 66 }) - txHash!: string; - - // Index of the log in the block. - @Column('integer') - index!: number; - - @Column('varchar', { length: 42 }) - contract!: string; - - @Column('varchar', { length: 256 }) - eventName!: string; - - @Column('text') - eventInfo!: string; - - @Column('text') - extraInfo!: string; - - @Column('text') - proof!: string; -} diff --git a/packages/erc20-watcher/src/entity/State.ts b/packages/erc20-watcher/src/entity/State.ts deleted file mode 100644 index bd12e427..00000000 --- a/packages/erc20-watcher/src/entity/State.ts +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, ManyToOne } from 'typeorm'; - -import { StateKind } from '@cerc-io/util'; - -import { BlockProgress } from './BlockProgress'; - -@Entity() -@Index(['cid'], { unique: true }) -@Index(['block', 'contractAddress']) -@Index(['block', 'contractAddress', 'kind'], { unique: true }) -export class State { - @PrimaryGeneratedColumn() - id!: number; - - @ManyToOne(() => BlockProgress, { onDelete: 'CASCADE' }) - block!: BlockProgress; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - cid!: string; - - @Column({ - type: 'enum', - enum: StateKind - }) - kind!: StateKind; - - @Column('bytea') - data!: Buffer; -} diff --git a/packages/erc20-watcher/src/entity/StateSyncStatus.ts b/packages/erc20-watcher/src/entity/StateSyncStatus.ts deleted file mode 100644 index c795212f..00000000 --- a/packages/erc20-watcher/src/entity/StateSyncStatus.ts +++ /dev/null @@ -1,17 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; - -@Entity() -export class StateSyncStatus { - @PrimaryGeneratedColumn() - id!: number; - - @Column('integer') - latestIndexedBlockNumber!: number; - - @Column('integer', { nullable: true }) - latestCheckpointBlockNumber!: number; -} diff --git a/packages/erc20-watcher/src/entity/SyncStatus.ts b/packages/erc20-watcher/src/entity/SyncStatus.ts deleted file mode 100644 index 82cd84a5..00000000 --- a/packages/erc20-watcher/src/entity/SyncStatus.ts +++ /dev/null @@ -1,43 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; - -import { SyncStatusInterface } from '@cerc-io/util'; - -@Entity() -export class SyncStatus implements SyncStatusInterface { - @PrimaryGeneratedColumn() - id!: number; - - // Latest block hash and number from the chain itself. - @Column('varchar', { length: 66 }) - chainHeadBlockHash!: string; - - @Column('integer') - chainHeadBlockNumber!: number; - - // Most recent block hash that's been indexed. - @Column('varchar', { length: 66 }) - latestIndexedBlockHash!: string; - - // Most recent block number that's been indexed. - @Column('integer') - latestIndexedBlockNumber!: number; - - // Most recent block hash and number that we can consider as part - // of the canonical/finalized chain. Reorgs older than this block - // cannot be processed and processing will halt. - @Column('varchar', { length: 66 }) - latestCanonicalBlockHash!: string; - - @Column('integer') - latestCanonicalBlockNumber!: number; - - @Column('varchar', { length: 66 }) - initialIndexedBlockHash!: string; - - @Column('integer') - initialIndexedBlockNumber!: number; -} diff --git a/packages/erc20-watcher/src/fill.ts b/packages/erc20-watcher/src/fill.ts deleted file mode 100644 index 185e0b64..00000000 --- a/packages/erc20-watcher/src/fill.ts +++ /dev/null @@ -1,26 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { FillCmd } from '@cerc-io/cli'; - -import { Database } from './database'; -import { Indexer } from './indexer'; - -const log = debug('vulcanize:fill'); - -export const main = async (): Promise => { - const fillCmd = new FillCmd(); - await fillCmd.init(Database); - await fillCmd.initIndexer(Indexer); - await fillCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(); -}); diff --git a/packages/erc20-watcher/src/index.ts b/packages/erc20-watcher/src/index.ts deleted file mode 100644 index faa5793e..00000000 --- a/packages/erc20-watcher/src/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -export * from './client'; diff --git a/packages/erc20-watcher/src/indexer.ts b/packages/erc20-watcher/src/indexer.ts deleted file mode 100644 index a3237ff3..00000000 --- a/packages/erc20-watcher/src/indexer.ts +++ /dev/null @@ -1,546 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -/* eslint-disable @typescript-eslint/no-unused-vars */ - -import assert from 'assert'; -import debug from 'debug'; -import { JsonFragment } from '@ethersproject/abi'; -import { DeepPartial, FindConditions, FindManyOptions } from 'typeorm'; -import JSONbig from 'json-bigint'; -import { ethers } from 'ethers'; -import { BaseProvider } from '@ethersproject/providers'; - -import { EthClient } from '@cerc-io/ipld-eth-client'; -import { MappingKey, StorageLayout } from '@cerc-io/solidity-mapper'; -import { - IndexerInterface, - Indexer as BaseIndexer, - ValueResult, - JobQueue, - Where, - QueryOptions, - ServerConfig, - StateStatus, - DatabaseInterface, - Clients, - StateKind -} from '@cerc-io/util'; - -import { Database, ENTITIES } from './database'; -import { Event } from './entity/Event'; -import { fetchTokenDecimals, fetchTokenName, fetchTokenSymbol, fetchTokenTotalSupply } from './utils'; -import { SyncStatus } from './entity/SyncStatus'; -import { StateSyncStatus } from './entity/StateSyncStatus'; -import artifacts from './artifacts/ERC20.json'; -import { BlockProgress } from './entity/BlockProgress'; -import { Contract } from './entity/Contract'; -import { State } from './entity/State'; - -const log = debug('vulcanize:indexer'); -const JSONbigNative = JSONbig({ useNativeBigInt: true }); - -const ETH_CALL_MODE = 'eth_call'; - -const TRANSFER_EVENT = 'Transfer'; -const APPROVAL_EVENT = 'Approval'; - -interface EventResult { - blockHash: string; - contract: string; - event: { - from?: string; - to?: string; - owner?: string; - spender?: string; - value?: bigint; - __typename: string; - } - proof?: string; -} - -export class Indexer implements IndexerInterface { - _db: Database; - _ethClient: EthClient; - _ethProvider: BaseProvider; - _baseIndexer: BaseIndexer; - _serverConfig: ServerConfig; - - _abi: JsonFragment[]; - _storageLayout: StorageLayout; - _contract: ethers.utils.Interface; - _serverMode: string; - - constructor (serverConfig: ServerConfig, db: DatabaseInterface, clients: Clients, ethProvider: BaseProvider, jobQueue: JobQueue) { - assert(db); - assert(clients.ethClient); - - this._db = db as Database; - this._ethClient = clients.ethClient; - this._ethProvider = ethProvider; - this._serverConfig = serverConfig; - this._serverMode = serverConfig.mode; - this._baseIndexer = new BaseIndexer(serverConfig, this._db, this._ethClient, this._ethProvider, jobQueue); - - const { abi, storageLayout } = artifacts; - - assert(abi); - assert(storageLayout); - - this._abi = abi; - this._storageLayout = storageLayout; - - this._contract = new ethers.utils.Interface(this._abi); - } - - get serverConfig (): ServerConfig { - return this._serverConfig; - } - - get storageLayoutMap (): Map { - return new Map([['ERC20', this._storageLayout]]); - } - - async init (): Promise { - await this._baseIndexer.fetchContracts(); - } - - getResultEvent (event: Event): EventResult { - const block = event.block; - const eventFields = JSON.parse(event.eventInfo); - - return { - blockHash: block.blockHash, - contract: event.contract, - event: { - __typename: `${event.eventName}Event`, - ...eventFields - }, - // TODO: Return proof only if requested. - proof: JSON.parse(event.proof) - }; - } - - async totalSupply (blockHash: string, token: string): Promise { - let result: ValueResult; - - if (this._serverMode === ETH_CALL_MODE) { - const value = await fetchTokenTotalSupply(this._ethProvider, blockHash, token); - - result = { value }; - } else { - result = await this._baseIndexer.getStorageValue(this._storageLayout, blockHash, token, '_totalSupply'); - } - - // https://github.com/GoogleChromeLabs/jsbi/issues/30#issuecomment-521460510 - log(JSONbigNative.stringify(result, null, 2)); - - return result; - } - - async balanceOf (blockHash: string, token: string, owner: string): Promise { - const entity = await this._db.getBalance({ blockHash, token, owner }); - if (entity) { - log('balanceOf: db hit'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('balanceOf: db miss, fetching from upstream server'); - let result: ValueResult; - - const { block: { number: blockNumber } } = await this._ethClient.getBlockByHash(blockHash); - - if (this._serverMode === ETH_CALL_MODE) { - const contract = new ethers.Contract(token, this._abi, this._ethProvider); - - // eth_call doesn't support calling method by blockHash https://eth.wiki/json-rpc/API#the-default-block-parameter - const value = await contract.balanceOf(owner, { blockTag: blockHash }); - - result = { - value: BigInt(value.toString()) - }; - } else { - result = await this._baseIndexer.getStorageValue(this._storageLayout, blockHash, token, '_balances', owner); - } - - log(JSONbigNative.stringify(result, null, 2)); - - const { value, proof } = result; - await this._db.saveBalance({ blockHash, blockNumber, token, owner, value: BigInt(value), proof: JSONbigNative.stringify(proof) }); - - return result; - } - - async allowance (blockHash: string, token: string, owner: string, spender: string): Promise { - const entity = await this._db.getAllowance({ blockHash, token, owner, spender }); - if (entity) { - log('allowance: db hit'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('allowance: db miss, fetching from upstream server'); - let result: ValueResult; - - const { block: { number: blockNumber } } = await this._ethClient.getBlockByHash(blockHash); - - if (this._serverMode === ETH_CALL_MODE) { - const contract = new ethers.Contract(token, this._abi, this._ethProvider); - const value = await contract.allowance(owner, spender, { blockTag: blockHash }); - - result = { - value: BigInt(value.toString()) - }; - } else { - result = await this._baseIndexer.getStorageValue(this._storageLayout, blockHash, token, '_allowances', owner, spender); - } - - // log(JSONbig.stringify(result, null, 2)); - - const { value, proof } = result; - await this._db.saveAllowance({ blockHash, blockNumber, token, owner, spender, value: BigInt(value), proof: JSONbigNative.stringify(proof) }); - - return result; - } - - async name (blockHash: string, token: string): Promise { - let result: ValueResult; - - if (this._serverMode === ETH_CALL_MODE) { - const value = await fetchTokenName(this._ethProvider, blockHash, token); - - result = { value }; - } else { - result = await this._baseIndexer.getStorageValue(this._storageLayout, blockHash, token, '_name'); - } - - // log(JSONbig.stringify(result, null, 2)); - - return result; - } - - async symbol (blockHash: string, token: string): Promise { - let result: ValueResult; - - if (this._serverMode === ETH_CALL_MODE) { - const value = await fetchTokenSymbol(this._ethProvider, blockHash, token); - - result = { value }; - } else { - result = await this._baseIndexer.getStorageValue(this._storageLayout, blockHash, token, '_symbol'); - } - - // log(JSONbig.stringify(result, null, 2)); - - return result; - } - - async decimals (blockHash: string, token: string): Promise { - let result: ValueResult; - - if (this._serverMode === ETH_CALL_MODE) { - const value = await fetchTokenDecimals(this._ethProvider, blockHash, token); - - result = { value }; - } else { - // Not a state variable, uses hardcoded return value in contract function. - // See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol#L86 - throw new Error('Not implemented.'); - } - - return result; - } - - async getStorageValue (storageLayout: StorageLayout, blockHash: string, contractAddress: string, variable: string, ...mappingKeys: MappingKey[]): Promise { - return this._baseIndexer.getStorageValue( - storageLayout, - blockHash, - contractAddress, - variable, - ...mappingKeys - ); - } - - async getEntitiesForBlock (blockHash: string, tableName: string): Promise { - return this._db.getEntitiesForBlock(blockHash, tableName); - } - - async processCanonicalBlock (blockHash: string, blockNumber: number): Promise { - // TODO Implement - } - - async processInitialState (contractAddress: string, blockHash: string): Promise { - // TODO: Call initial state hook. - return undefined; - } - - async processStateCheckpoint (contractAddress: string, blockHash: string): Promise { - // TODO: Call checkpoint hook. - return false; - } - - async processCheckpoint (blockHash: string): Promise { - // TODO Implement - } - - async processCLICheckpoint (contractAddress: string, blockHash?: string): Promise { - // TODO Implement - return undefined; - } - - async getLatestState (contractAddress: string, kind: StateKind | null, blockNumber?: number): Promise { - // TODO Implement - return undefined; - } - - async getStateByCID (cid: string): Promise { - // TODO Implement - return undefined; - } - - async getStates (where: FindConditions): Promise { - // TODO Implement - return []; - } - - async createDiffStaged (contractAddress: string, blockHash: string, data: any): Promise { - // TODO Implement - } - - async createDiff (contractAddress: string, blockHash: string, data: any): Promise { - // TODO Implement - } - - async createCheckpoint (contractAddress: string, blockHash: string): Promise { - // TODO Implement - return undefined; - } - - async saveOrUpdateState (state: State): Promise { - return {} as State; - } - - async removeStates (blockNumber: number, kind: StateKind): Promise { - // TODO Implement - } - - getStateData (state: State): any { - return this._baseIndexer.getStateData(state); - } - - async triggerIndexingOnEvent (event: Event): Promise { - const { eventName, eventInfo, contract: token, block: { blockHash } } = event; - const eventFields = JSON.parse(eventInfo); - - // What data we index depends on the kind of event. - switch (eventName) { - case TRANSFER_EVENT: { - // On a transfer, balances for both parties change. - // Therefore, trigger indexing for both sender and receiver. - const { from, to } = eventFields; - await this.balanceOf(blockHash, token, from); - await this.balanceOf(blockHash, token, to); - - break; - } - case APPROVAL_EVENT: { - // Update allowance for (owner, spender) combination. - const { owner, spender } = eventFields; - await this.allowance(blockHash, token, owner, spender); - - break; - } - } - } - - async processEvent (event: Event): Promise { - // Trigger indexing of data based on the event. - await this.triggerIndexingOnEvent(event); - } - - async processBlock (blockProgress: BlockProgress): Promise { - console.time('time:indexer#processBlock-init_state'); - // Call a function to create initial state for contracts. - await this._baseIndexer.createInit(this, blockProgress.blockHash, blockProgress.blockNumber); - console.time('time:indexer#processBlock-init_state'); - } - - parseEventNameAndArgs (kind: string, logObj: any): any { - const { topics, data } = logObj; - const logDescription = this._contract.parseLog({ data, topics }); - - const { eventName, eventInfo } = this._baseIndexer.parseEvent(logDescription); - - return { eventName, eventInfo }; - } - - async getStateSyncStatus (): Promise { - return this._db.getStateSyncStatus(); - } - - async updateStateSyncStatusIndexedBlock (blockNumber: number, force?: boolean): Promise { - // TODO Implement - return {} as StateSyncStatus; - } - - async updateStateSyncStatusCheckpointBlock (blockNumber: number, force?: boolean): Promise { - // TODO Implement - return {} as StateSyncStatus; - } - - async getLatestStateIndexedBlock (): Promise { - // TODO Implement - return {} as BlockProgress; - } - - async getLatestCanonicalBlock (): Promise { - const syncStatus = await this.getSyncStatus(); - assert(syncStatus); - - const latestCanonicalBlock = await this.getBlockProgress(syncStatus.latestCanonicalBlockHash); - assert(latestCanonicalBlock); - - return latestCanonicalBlock; - } - - async getEventsByFilter (blockHash: string, contract: string, name?: string): Promise> { - return this._baseIndexer.getEventsByFilter(blockHash, contract, name); - } - - isWatchedContract (address : string): Contract | undefined { - return this._baseIndexer.isWatchedContract(address); - } - - async watchContract (address: string, kind: string, checkpoint: boolean, startingBlock: number): Promise { - return this._baseIndexer.watchContract(address, kind, checkpoint, startingBlock); - } - - updateStateStatusMap (address: string, stateStatus: StateStatus): void { - this._baseIndexer.updateStateStatusMap(address, stateStatus); - } - - cacheContract (contract: Contract): void { - return this._baseIndexer.cacheContract(contract); - } - - async saveEventEntity (dbEvent: Event): Promise { - return this._baseIndexer.saveEventEntity(dbEvent); - } - - async getProcessedBlockCountForRange (fromBlockNumber: number, toBlockNumber: number): Promise<{ expected: number, actual: number }> { - return this._baseIndexer.getProcessedBlockCountForRange(fromBlockNumber, toBlockNumber); - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise> { - return this._baseIndexer.getEventsInRange(fromBlockNumber, toBlockNumber); - } - - async updateSyncStatusIndexedBlock (blockHash: string, blockNumber: number, force = false): Promise { - return this._baseIndexer.updateSyncStatusIndexedBlock(blockHash, blockNumber, force); - } - - async updateSyncStatusChainHead (blockHash: string, blockNumber: number, force = false): Promise { - return this._baseIndexer.updateSyncStatusChainHead(blockHash, blockNumber, force); - } - - async updateSyncStatusCanonicalBlock (blockHash: string, blockNumber: number, force = false): Promise { - return this._baseIndexer.updateSyncStatusCanonicalBlock(blockHash, blockNumber, force); - } - - async getSyncStatus (): Promise { - return this._baseIndexer.getSyncStatus(); - } - - async getBlocks (blockFilter: { blockHash?: string, blockNumber?: number }): Promise { - return this._baseIndexer.getBlocks(blockFilter); - } - - async getEvent (id: string): Promise { - return this._baseIndexer.getEvent(id); - } - - async getBlockProgress (blockHash: string): Promise { - return this._baseIndexer.getBlockProgress(blockHash); - } - - async getBlockProgressEntities (where: FindConditions, options: FindManyOptions): Promise { - return this._baseIndexer.getBlockProgressEntities(where, options); - } - - async getBlocksAtHeight (height: number, isPruned: boolean): Promise { - return this._baseIndexer.getBlocksAtHeight(height, isPruned); - } - - async saveBlockAndFetchEvents (block: DeepPartial): Promise<[BlockProgress, DeepPartial[]]> { - return this._saveBlockAndFetchEvents(block); - } - - async getBlockEvents (blockHash: string, where: Where, queryOptions: QueryOptions): Promise> { - return this._baseIndexer.getBlockEvents(blockHash, where, queryOptions); - } - - async removeUnknownEvents (block: BlockProgress): Promise { - return this._baseIndexer.removeUnknownEvents(Event, block); - } - - async markBlocksAsPruned (blocks: BlockProgress[]): Promise { - return this._baseIndexer.markBlocksAsPruned(blocks); - } - - async updateBlockProgress (block: BlockProgress, lastProcessedEventIndex: number): Promise { - return this._baseIndexer.updateBlockProgress(block, lastProcessedEventIndex); - } - - async getAncestorAtDepth (blockHash: string, depth: number): Promise { - return this._baseIndexer.getAncestorAtDepth(blockHash, depth); - } - - async resetWatcherToBlock (blockNumber: number): Promise { - const entities = [...ENTITIES]; - await this._baseIndexer.resetWatcherToBlock(blockNumber, entities); - } - - async _saveBlockAndFetchEvents ({ - cid: blockCid, - blockHash, - blockNumber, - blockTimestamp, - parentHash - }: DeepPartial): Promise<[BlockProgress, DeepPartial[]]> { - assert(blockHash); - assert(blockNumber); - - const dbEvents = await this._baseIndexer.fetchEvents(blockHash, blockNumber, this.parseEventNameAndArgs.bind(this)); - - const dbTx = await this._db.createTransactionRunner(); - try { - const block = { - cid: blockCid, - blockHash, - blockNumber, - blockTimestamp, - parentHash - }; - - console.time('time:indexer#_fetchAndSaveEvents-save-block-events'); - const blockProgress = await this._db.saveBlockWithEvents(dbTx, block, dbEvents); - await dbTx.commitTransaction(); - console.timeEnd('time:indexer#_fetchAndSaveEvents-save-block-events'); - - return [blockProgress, []]; - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - } -} diff --git a/packages/erc20-watcher/src/job-runner.ts b/packages/erc20-watcher/src/job-runner.ts deleted file mode 100644 index 16c58d8d..00000000 --- a/packages/erc20-watcher/src/job-runner.ts +++ /dev/null @@ -1,34 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import debug from 'debug'; - -import { JobRunnerCmd } from '@cerc-io/cli'; -import { JobRunner } from '@cerc-io/util'; - -import { Indexer } from './indexer'; -import { Database } from './database'; - -const log = debug('vulcanize:job-runner'); - -export const main = async (): Promise => { - const jobRunnerCmd = new JobRunnerCmd(); - await jobRunnerCmd.init(Database); - await jobRunnerCmd.initIndexer(Indexer); - - await jobRunnerCmd.exec(async (jobRunner: JobRunner): Promise => { - await jobRunner.subscribeBlockProcessingQueue(); - await jobRunner.subscribeEventProcessingQueue(); - }); -}; - -main().then(() => { - log('Starting job runner...'); -}).catch(err => { - log(err); -}); - -process.on('uncaughtException', err => { - log('uncaughtException', err); -}); diff --git a/packages/erc20-watcher/src/queries.ts b/packages/erc20-watcher/src/queries.ts deleted file mode 100644 index e84d7bca..00000000 --- a/packages/erc20-watcher/src/queries.ts +++ /dev/null @@ -1,94 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { gql } from 'graphql-request'; - -export const queryTotalSupply = gql` -query getTotalSupply($blockHash: String!, $token: String!) { - totalSupply(blockHash: $blockHash, token: $token) { - value - proof { - data - } - } -} -`; - -export const queryBalanceOf = gql` -query getBalance($blockHash: String!, $token: String!, $owner: String!) { - balanceOf(blockHash: $blockHash, token: $token, owner: $owner) { - value - proof { - data - } - } -} -`; - -export const queryAllowance = gql` -query getAllowance($blockHash: String!, $token: String!, $owner: String!, $spender: String!) { - allowance(blockHash: $blockHash, token: $token, owner: $owner, spender: $spender) { - value - proof { - data - } - } -} -`; - -export const queryName = gql` -query getName($blockHash: String!, $token: String!) { - name(blockHash: $blockHash, token: $token) { - value - proof { - data - } - } -} -`; - -export const querySymbol = gql` -query getSymbol($blockHash: String!, $token: String!) { - symbol(blockHash: $blockHash, token: $token) { - value - proof { - data - } - } -} -`; - -export const queryDecimals = gql` -query getDecimals($blockHash: String!, $token: String!) { - decimals(blockHash: $blockHash, token: $token) { - value - proof { - data - } - } -} -`; - -export const queryEvents = gql` -query getEvents($blockHash: String!, $token: String!) { - events(blockHash: $blockHash, token: $token) { - event { - __typename - ... on TransferEvent { - from - to - value - } - ... on ApprovalEvent { - owner - spender - value - } - } - proof { - data - } - } -} -`; diff --git a/packages/erc20-watcher/src/resolvers.ts b/packages/erc20-watcher/src/resolvers.ts deleted file mode 100644 index fa7d54e3..00000000 --- a/packages/erc20-watcher/src/resolvers.ts +++ /dev/null @@ -1,108 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import BigInt from 'apollo-type-bigint'; -import debug from 'debug'; - -import { EventWatcher, IndexerInterface, ValueResult } from '@cerc-io/util'; - -import { Indexer } from './indexer'; -import { CONTRACT_KIND } from './utils/index'; - -const log = debug('vulcanize:resolver'); - -export const createResolvers = async (indexerArg: IndexerInterface, eventWatcher: EventWatcher): Promise => { - const indexer = indexerArg as Indexer; - - return { - BigInt: new BigInt('bigInt'), - - TokenEvent: { - __resolveType: (obj: any) => { - assert(obj.__typename); - - return obj.__typename; - } - }, - - Subscription: { - onEvent: { - subscribe: () => eventWatcher.getEventIterator() - } - }, - - Mutation: { - watchToken: async (_: any, { token, checkpoint = false, startingBlock = 1 }: { token: string, checkpoint: boolean, startingBlock: number }): Promise => { - log('watchToken', token, checkpoint, startingBlock); - await indexer.watchContract(token, CONTRACT_KIND, checkpoint, startingBlock); - - return true; - } - }, - - Query: { - - totalSupply: (_: any, { blockHash, token }: { blockHash: string, token: string }): Promise => { - log('totalSupply', blockHash, token); - return indexer.totalSupply(blockHash, token); - }, - - balanceOf: async (_: any, { blockHash, token, owner }: { blockHash: string, token: string, owner: string }) => { - log('balanceOf', blockHash, token, owner); - return indexer.balanceOf(blockHash, token, owner); - }, - - allowance: async (_: any, { blockHash, token, owner, spender }: { blockHash: string, token: string, owner: string, spender: string }) => { - log('allowance', blockHash, token, owner, spender); - return indexer.allowance(blockHash, token, owner, spender); - }, - - name: (_: any, { blockHash, token }: { blockHash: string, token: string }) => { - log('name', blockHash, token); - return indexer.name(blockHash, token); - }, - - symbol: (_: any, { blockHash, token }: { blockHash: string, token: string }) => { - log('symbol', blockHash, token); - return indexer.symbol(blockHash, token); - }, - - decimals: (_: any, { blockHash, token }: { blockHash: string, token: string }) => { - log('decimals', blockHash, token); - return indexer.decimals(blockHash, token); - }, - - events: async (_: any, { blockHash, token, name }: { blockHash: string, token: string, name: string }) => { - log('events', blockHash, token, name || ''); - - const block = await indexer.getBlockProgress(blockHash); - if (!block || !block.isComplete) { - throw new Error(`Block hash ${blockHash} number ${block?.blockNumber} not processed yet`); - } - - const events = await indexer.getEventsByFilter(blockHash, token, name); - return events.map(event => indexer.getResultEvent(event)); - }, - - eventsInRange: async (_: any, { fromBlockNumber, toBlockNumber }: { fromBlockNumber: number, toBlockNumber: number }) => { - log('eventsInRange', fromBlockNumber, toBlockNumber); - - const { expected, actual } = await indexer.getProcessedBlockCountForRange(fromBlockNumber, toBlockNumber); - if (expected !== actual) { - throw new Error(`Range not available, expected ${expected}, got ${actual} blocks in range`); - } - - const events = await indexer.getEventsInRange(fromBlockNumber, toBlockNumber); - return events.map(event => indexer.getResultEvent(event)); - }, - - getSyncStatus: async () => { - log('getSyncStatus'); - - return indexer.getSyncStatus(); - } - } - }; -}; diff --git a/packages/erc20-watcher/src/schema.ts b/packages/erc20-watcher/src/schema.ts deleted file mode 100644 index cbb44c3f..00000000 --- a/packages/erc20-watcher/src/schema.ts +++ /dev/null @@ -1,168 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { gql } from '@apollo/client/core'; - -export default gql` -# -# ERC20 GQL schema -# -# See: https://eips.ethereum.org/EIPS/eip-20 -# ABI: https://ethereumdev.io/abi-for-erc20-contract-on-ethereum/ -# - -# Types - -# Support uint256 values. -scalar BigInt - -# Proof for returned data. Serialized blob for now. -# Will be converted into a well defined structure later. -type Proof { - data: String! -} - -# Result type, with proof, for string method return values. -type ResultString { - value: String - - # Proof from state/storage trie. - proof: Proof -} - -# Result type, with proof, for uint256 method return values. -type ResultUInt256 { - value: BigInt! - - # Proof from state/storage trie. - proof: Proof -} - -# Transfer Event -type TransferEvent { - from: String! - to: String! - value: BigInt! -} - -# Approval Event -type ApprovalEvent { - owner: String! - spender: String! - value: BigInt! -} - -# All possible event types fired by an ERC20 contract. -union TokenEvent = TransferEvent | ApprovalEvent - -# Result type, with proof, for event return values. -type ResultEvent { - blockHash: String! - contract: String! - - event: TokenEvent! - # Proof from receipts trie. - proof: Proof -} - -type SyncStatus { - latestIndexedBlockHash: String! - latestIndexedBlockNumber: Int! - latestCanonicalBlockHash: String! - latestCanonicalBlockNumber: Int! -} - -# -# Queries -# - -type Query { - - # - # Interface of the ERC20 standard as defined in the EIP. - # https://docs.openzeppelin.com/contracts/2.x/api/token/erc20#IERC20 - # - - totalSupply( - blockHash: String! - token: String! - ): ResultUInt256! - - balanceOf( - blockHash: String! - token: String! - - owner: String! - ): ResultUInt256! - - allowance( - blockHash: String! - token: String! - - owner: String! - spender: String! - ): ResultUInt256! - - # - # Optional functions from the ERC20 standard. - # https://docs.openzeppelin.com/contracts/2.x/api/token/erc20#ERC20Detailed - # - - name( - blockHash: String! - token: String! - ): ResultString! - - symbol( - blockHash: String! - token: String! - ): ResultString! - - decimals( - blockHash: String! - token: String! - ): ResultUInt256! - - # - # Additional watcher queries. - # - - # Get token events at a certain block, optionally filter by event name. - events( - blockHash: String! - token: String! - name: String - ): [ResultEvent!] - - # Get token events in a given block range. - eventsInRange( - fromBlockNumber: Int! - toBlockNumber: Int! - ): [ResultEvent!] - - getSyncStatus: SyncStatus -} - -# -# Subscriptions -# -type Subscription { - - # Watch for token events (at head of chain). - onEvent: ResultEvent! -} - -# -# Mutations -# -type Mutation { - - # Actively watch and index data for the token. - watchToken( - token: String! - checkpoint: Boolean - startingBlock: Int - ): Boolean! -} -`; diff --git a/packages/erc20-watcher/src/server.ts b/packages/erc20-watcher/src/server.ts deleted file mode 100644 index 4ae6de5e..00000000 --- a/packages/erc20-watcher/src/server.ts +++ /dev/null @@ -1,29 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { ServerCmd } from '@cerc-io/cli'; - -import typeDefs from './schema'; -import { createResolvers } from './resolvers'; -import { Indexer } from './indexer'; -import { Database } from './database'; - -const log = debug('vulcanize:server'); - -export const main = async (): Promise => { - const serverCmd = new ServerCmd(); - await serverCmd.init(Database); - await serverCmd.initIndexer(Indexer); - - return serverCmd.exec(createResolvers, typeDefs); -}; - -main().then(() => { - log('Starting server...'); -}).catch(err => { - log(err); -}); diff --git a/packages/erc20-watcher/src/types/common/main.d.ts b/packages/erc20-watcher/src/types/common/main.d.ts deleted file mode 100644 index aa0c891f..00000000 --- a/packages/erc20-watcher/src/types/common/main.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -// https://medium.com/@steveruiz/using-a-javascript-library-without-type-declarations-in-a-typescript-project-3643490015f3 -declare module 'canonical-json' diff --git a/packages/erc20-watcher/src/types/common/package.json b/packages/erc20-watcher/src/types/common/package.json deleted file mode 100644 index 5861d0f0..00000000 --- a/packages/erc20-watcher/src/types/common/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "common", - "version": "0.1.0", - "license": "AGPL-3.0", - "typings": "main.d.ts" -} diff --git a/packages/erc20-watcher/src/utils/index.ts b/packages/erc20-watcher/src/utils/index.ts deleted file mode 100644 index 89332401..00000000 --- a/packages/erc20-watcher/src/utils/index.ts +++ /dev/null @@ -1,118 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Contract, utils } from 'ethers'; -import { BaseProvider } from '@ethersproject/providers'; - -import { abi } from '../artifacts/ERC20.json'; -import ERC20SymbolBytesABI from '../artifacts/ERC20SymbolBytes.json'; -import ERC20NameBytesABI from '../artifacts/ERC20NameBytes.json'; -import { StaticTokenDefinition } from './static-token-definition'; - -export const CONTRACT_KIND = 'token'; - -export const fetchTokenSymbol = async (ethProvider: BaseProvider, blockHash: string, tokenAddress: string): Promise => { - const contract = new Contract(tokenAddress, abi, ethProvider); - const contractSymbolBytes = new Contract(tokenAddress, ERC20SymbolBytesABI, ethProvider); - let symbolValue = 'unknown'; - - // Try types string and bytes32 for symbol. - try { - const result = await contract.symbol({ blockTag: blockHash }); - symbolValue = result; - } catch (error) { - try { - const result = await contractSymbolBytes.symbol({ blockTag: blockHash }); - - // For broken pairs that have no symbol function exposed. - if (!isNullEthValue(utils.hexlify(result))) { - symbolValue = utils.parseBytes32String(result); - } else { - // Try with the static definition. - const staticTokenDefinition = StaticTokenDefinition.fromAddress(tokenAddress); - - if (staticTokenDefinition !== null) { - symbolValue = staticTokenDefinition.symbol; - } - } - } catch (error) { - // symbolValue is unknown if the calls revert. - } - } - - return symbolValue; -}; - -export const fetchTokenName = async (ethProvider: BaseProvider, blockHash: string, tokenAddress: string): Promise => { - const contract = new Contract(tokenAddress, abi, ethProvider); - const contractNameBytes = new Contract(tokenAddress, ERC20NameBytesABI, ethProvider); - let nameValue = 'unknown'; - - // Try types string and bytes32 for name. - try { - const result = await contract.name({ blockTag: blockHash }); - nameValue = result; - } catch (error) { - try { - const result = await contractNameBytes.name({ blockTag: blockHash }); - - // For broken pairs that have no name function exposed. - if (!isNullEthValue(utils.hexlify(result))) { - nameValue = utils.parseBytes32String(result); - } else { - // Try with the static definition. - const staticTokenDefinition = StaticTokenDefinition.fromAddress(tokenAddress); - - if (staticTokenDefinition !== null) { - nameValue = staticTokenDefinition.name; - } - } - } catch (error) { - // nameValue is unknown if the calls revert. - } - } - - return nameValue; -}; - -export const fetchTokenTotalSupply = async (ethProvider: BaseProvider, blockHash: string, tokenAddress: string): Promise => { - const contract = new Contract(tokenAddress, abi, ethProvider); - let totalSupplyValue = null; - - try { - const result = await contract.totalSupply({ blockTag: blockHash }); - totalSupplyValue = result.toString(); - } catch (error) { - totalSupplyValue = 0; - } - - return BigInt(totalSupplyValue); -}; - -export const fetchTokenDecimals = async (ethProvider: BaseProvider, blockHash: string, tokenAddress: string): Promise => { - const contract = new Contract(tokenAddress, abi, ethProvider); - - // Try types uint8 for decimals. - let decimalValue = null; - - try { - const result = await contract.decimals({ blockTag: blockHash }); - decimalValue = result.toString(); - } catch (error) { - // Try with the static definition. - const staticTokenDefinition = StaticTokenDefinition.fromAddress(tokenAddress); - - if (staticTokenDefinition != null) { - return staticTokenDefinition.decimals; - } - - decimalValue = 0; - } - - return BigInt(decimalValue); -}; - -const isNullEthValue = (value: string): boolean => { - return value === '0x0000000000000000000000000000000000000000000000000000000000000001'; -}; diff --git a/packages/erc20-watcher/src/utils/static-token-definition.ts b/packages/erc20-watcher/src/utils/static-token-definition.ts deleted file mode 100644 index 34914857..00000000 --- a/packages/erc20-watcher/src/utils/static-token-definition.ts +++ /dev/null @@ -1,99 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { utils } from 'ethers'; - -// Initialize a Token Definition with the attributes. -export class StaticTokenDefinition { - address : string; - symbol: string; - name: string; - decimals: bigint; - - // Initialize a Token Definition with its attributes. - constructor (address: string, symbol: string, name: string, decimals: bigint) { - this.address = address; - this.symbol = symbol; - this.name = name; - this.decimals = decimals; - } - - // Get all tokens with a static defintion - static getStaticDefinitions (): Array { - const staticDefinitions = []; - - // Add DGD. - const tokenDGD = new StaticTokenDefinition( - utils.getAddress('0xe0b7927c4af23765cb51314a0e0521a9645f0e2a'), - 'DGD', - 'DGD', - BigInt(9) - ); - staticDefinitions.push(tokenDGD); - - // Add AAVE. - const tokenAAVE = new StaticTokenDefinition( - utils.getAddress('0x7fc66500c84a76ad7e9c93437bfc5ac33e2ddae9'), - 'AAVE', - 'Aave Token', - BigInt(18) - ); - staticDefinitions.push(tokenAAVE); - - // Add LIF. - const tokenLIF = new StaticTokenDefinition( - utils.getAddress('0xeb9951021698b42e4399f9cbb6267aa35f82d59d'), - 'LIF', - 'Lif', - BigInt(18) - ); - staticDefinitions.push(tokenLIF); - - // Add SVD. - const tokenSVD = new StaticTokenDefinition( - utils.getAddress('0xbdeb4b83251fb146687fa19d1c660f99411eefe3'), - 'SVD', - 'savedroid', - BigInt(18) - ); - staticDefinitions.push(tokenSVD); - - // Add TheDAO. - const tokenTheDAO = new StaticTokenDefinition( - utils.getAddress('0xbb9bc244d798123fde783fcc1c72d3bb8c189413'), - 'TheDAO', - 'TheDAO', - BigInt(16) - ); - staticDefinitions.push(tokenTheDAO); - - // Add HPB. - const tokenHPB = new StaticTokenDefinition( - utils.getAddress('0x38c6a68304cdefb9bec48bbfaaba5c5b47818bb2'), - 'HPB', - 'HPBCoin', - BigInt(18) - ); - staticDefinitions.push(tokenHPB); - - return staticDefinitions; - } - - // Helper for hardcoded tokens. - static fromAddress (tokenAddress: string) : StaticTokenDefinition | null { - const staticDefinitions = this.getStaticDefinitions(); - const tokenAddressHex = utils.hexlify(tokenAddress); - - // Search the definition using the address. - for (let i = 0; i < staticDefinitions.length; i++) { - const staticDefinition = staticDefinitions[i]; - if (utils.getAddress(utils.hexlify(staticDefinition.address)) === utils.getAddress(tokenAddressHex)) { - return staticDefinition; - } - } - - // If not found, return null. - return null; - } -} diff --git a/packages/erc20-watcher/test/contracts/GLDToken.sol b/packages/erc20-watcher/test/contracts/GLDToken.sol deleted file mode 100644 index 1d8e68b3..00000000 --- a/packages/erc20-watcher/test/contracts/GLDToken.sol +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0 -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract GLDToken is ERC20 { - constructor(uint256 initialSupply) ERC20("Gold", "GLD") { - _mint(msg.sender, initialSupply); - } -} diff --git a/packages/erc20-watcher/test/tasks/account.ts b/packages/erc20-watcher/test/tasks/account.ts deleted file mode 100644 index 78a15e35..00000000 --- a/packages/erc20-watcher/test/tasks/account.ts +++ /dev/null @@ -1,12 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { task } from 'hardhat/config'; -import '@nomiclabs/hardhat-ethers'; - -task('account', 'Prints the account', async (taskArgs, hre) => { - const [account] = await hre.ethers.getSigners(); - - console.log(account.address); -}); diff --git a/packages/erc20-watcher/test/tasks/block-latest.ts b/packages/erc20-watcher/test/tasks/block-latest.ts deleted file mode 100644 index a6337a26..00000000 --- a/packages/erc20-watcher/test/tasks/block-latest.ts +++ /dev/null @@ -1,18 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { task } from 'hardhat/config'; -import '@nomiclabs/hardhat-ethers'; - -task( - 'block-latest', - 'Prints the current block info', - async (_, { ethers }) => { - const blockNumber = await ethers.provider.getBlockNumber(); - const block = await ethers.provider.getBlock(blockNumber); - - console.log('Block Number:', blockNumber); - console.log('Block Hash:', block.hash); - } -); diff --git a/packages/erc20-watcher/test/tasks/token-approve.ts b/packages/erc20-watcher/test/tasks/token-approve.ts deleted file mode 100644 index 70096fd2..00000000 --- a/packages/erc20-watcher/test/tasks/token-approve.ts +++ /dev/null @@ -1,34 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { task, types } from 'hardhat/config'; -import '@nomiclabs/hardhat-ethers'; -import { ContractTransaction, BigNumber } from 'ethers'; - -const DEFAULT_APPROVE_AMOUNT = '1000000000000000000000000'; - -task('token-approve', 'Move tokens to recipient') - .addParam('token', 'Token contract address', undefined, types.string) - .addParam('spender', 'Spender address', undefined, types.string) - .addParam('amount', 'Token amount to transfer', DEFAULT_APPROVE_AMOUNT, types.string) - .setAction(async (args, hre) => { - const { token: tokenAddress, amount, spender } = args; - await hre.run('compile'); - const Token = await hre.ethers.getContractFactory('GLDToken'); - const token = Token.attach(tokenAddress); - - const transaction: ContractTransaction = await token.approve(spender, BigNumber.from(amount)); - const receipt = await transaction.wait(); - - if (receipt.events) { - const TransferEvent = receipt.events.find(el => el.event === 'Approval'); - - if (TransferEvent && TransferEvent.args) { - console.log('Approval Event at block:', receipt.blockNumber, receipt.blockHash); - console.log('owner:', TransferEvent.args.owner.toString()); - console.log('spender:', TransferEvent.args.spender.toString()); - console.log('value:', TransferEvent.args.value.toString()); - } - } - }); diff --git a/packages/erc20-watcher/test/tasks/token-deploy.ts b/packages/erc20-watcher/test/tasks/token-deploy.ts deleted file mode 100644 index 28a85adb..00000000 --- a/packages/erc20-watcher/test/tasks/token-deploy.ts +++ /dev/null @@ -1,21 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { task, types } from 'hardhat/config'; -import '@nomiclabs/hardhat-ethers'; - -const DEFAULT_INITIAL_SUPPLY = '1000000000000000000000'; - -task('token-deploy', 'Deploys GLD token') - .addOptionalParam('initialSupply', 'Set total supply', DEFAULT_INITIAL_SUPPLY, types.string) - .setAction(async (args, hre) => { - const { initialSupply } = args; - await hre.run('compile'); - const Token = await hre.ethers.getContractFactory('GLDToken'); - const token = await Token.deploy(hre.ethers.BigNumber.from(initialSupply)); - - const receipt = await token.deployTransaction.wait(); - console.log('GLD Token deployed to:', token.address); - console.log('Deployed at block:', receipt.blockNumber, receipt.blockHash); - }); diff --git a/packages/erc20-watcher/test/tasks/token-transfer-from.ts b/packages/erc20-watcher/test/tasks/token-transfer-from.ts deleted file mode 100644 index 005b1c3b..00000000 --- a/packages/erc20-watcher/test/tasks/token-transfer-from.ts +++ /dev/null @@ -1,37 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { task, types } from 'hardhat/config'; -import '@nomiclabs/hardhat-ethers'; -import { ContractTransaction } from 'ethers'; - -task('token-transfer-from', 'Send tokens as spender') - .addParam('token', 'Token contract address', undefined, types.string) - .addParam('spenderKey', 'Spender private key', undefined, types.string) - .addParam('to', 'Transfer recipient address', undefined, types.string) - .addParam('amount', 'Token amount to transfer', undefined, types.int) - .setAction(async (args, hre) => { - const { token: tokenAddress, to, amount, spenderKey } = args; - await hre.run('compile'); - const [owner] = await hre.ethers.getSigners(); - const wallet = new hre.ethers.Wallet(spenderKey, hre.ethers.provider); - const Token = await hre.ethers.getContractFactory('GLDToken'); - let token = Token.attach(tokenAddress); - - token = token.connect(wallet); - const transaction: ContractTransaction = await token.transferFrom(owner.address, to, amount); - - const receipt = await transaction.wait(); - - if (receipt.events) { - const TransferEvent = receipt.events.find(el => el.event === 'Transfer'); - - if (TransferEvent && TransferEvent.args) { - console.log('Transfer Event at block:', receipt.blockNumber, receipt.blockHash); - console.log('from:', TransferEvent.args.from.toString()); - console.log('to:', TransferEvent.args.to.toString()); - console.log('value:', TransferEvent.args.value.toString()); - } - } - }); diff --git a/packages/erc20-watcher/test/tasks/token-transfer.ts b/packages/erc20-watcher/test/tasks/token-transfer.ts deleted file mode 100644 index fb281733..00000000 --- a/packages/erc20-watcher/test/tasks/token-transfer.ts +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { task, types } from 'hardhat/config'; -import '@nomiclabs/hardhat-ethers'; -import { ContractTransaction } from 'ethers'; - -task('token-transfer', 'Move tokens to recipient') - .addParam('token', 'Token contract address', undefined, types.string) - .addParam('to', 'Transfer recipient address', undefined, types.string) - .addParam('amount', 'Token amount to transfer', undefined, types.int) - .setAction(async (args, hre) => { - const { token: tokenAddress, to, amount } = args; - await hre.run('compile'); - const Token = await hre.ethers.getContractFactory('GLDToken'); - const token = Token.attach(tokenAddress); - - const transaction: ContractTransaction = await token.transfer(to, amount); - - const receipt = await transaction.wait(); - - if (receipt.events) { - const TransferEvent = receipt.events.find(el => el.event === 'Transfer'); - - if (TransferEvent && TransferEvent.args) { - console.log('Transfer Event at block:', receipt.blockNumber, receipt.blockHash); - console.log('from:', TransferEvent.args.from.toString()); - console.log('to:', TransferEvent.args.to.toString()); - console.log('value:', TransferEvent.args.value.toString()); - } - } - }); diff --git a/packages/erc20-watcher/tsconfig.json b/packages/erc20-watcher/tsconfig.json deleted file mode 100644 index 08597027..00000000 --- a/packages/erc20-watcher/tsconfig.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "compilerOptions": { - /* Visit https://aka.ms/tsconfig.json to read more about this file */ - - /* Basic Options */ - // "incremental": true, /* Enable incremental compilation */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ - "lib": [ "ES5", "ES6", "ES2020" ], /* Specify library files to be included in the compilation. */ - // "allowJs": true, /* Allow javascript files to be compiled. */ - // "checkJs": true, /* Report errors in .js files. */ - // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ - "declaration": true, /* Generates corresponding '.d.ts' file. */ - // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - "sourceMap": true, /* Generates corresponding '.map' file. */ - // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "dist", /* Redirect output structure to the directory. */ - // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - // "composite": true, /* Enable project compilation */ - // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ - // "removeComments": true, /* Do not emit comments to output. */ - // "noEmit": true, /* Do not emit outputs. */ - // "importHelpers": true, /* Import emit helpers from 'tslib'. */ - "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ - // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* Enable strict null checks. */ - // "strictFunctionTypes": true, /* Enable strict checking of function types. */ - // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ - // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ - // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - - /* Additional Checks */ - // "noUnusedLocals": true, /* Report errors on unused locals. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ - - /* Module Resolution Options */ - "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ - // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ - // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ - "typeRoots": [ - "./src/types" - ], /* List of folders to include type definitions from. */ - // "types": [], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ - // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - - /* Source Map Options */ - // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ - // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - - /* Experimental Options */ - "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ - // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - - /* Advanced Options */ - "skipLibCheck": true, /* Skip type checking of declaration files. */ - "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ - "resolveJsonModule": true /* Enabling the option allows importing JSON, and validating the types in that JSON file. */ - }, - "include": ["src/**/*"], - "exclude": ["dist", "src/**/*.test.ts"] -} diff --git a/packages/erc721-watcher/.eslintignore b/packages/erc721-watcher/.eslintignore deleted file mode 100644 index 55cb5225..00000000 --- a/packages/erc721-watcher/.eslintignore +++ /dev/null @@ -1,2 +0,0 @@ -# Don't lint build output. -dist diff --git a/packages/erc721-watcher/.eslintrc.json b/packages/erc721-watcher/.eslintrc.json deleted file mode 100644 index a2b842c2..00000000 --- a/packages/erc721-watcher/.eslintrc.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "env": { - "browser": true, - "es2021": true - }, - "extends": [ - "semistandard", - "plugin:@typescript-eslint/recommended" - ], - "parser": "@typescript-eslint/parser", - "parserOptions": { - "ecmaVersion": 12, - "sourceType": "module" - }, - "plugins": [ - "@typescript-eslint" - ], - "rules": { - "indent": ["error", 2, { "SwitchCase": 1 }], - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/explicit-module-boundary-types": [ - "warn", - { - "allowArgumentsExplicitlyTypedAsAny": true - } - ] - } -} diff --git a/packages/erc721-watcher/.gitignore b/packages/erc721-watcher/.gitignore deleted file mode 100644 index d3a728b9..00000000 --- a/packages/erc721-watcher/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -#Hardhat files -cache -artifacts diff --git a/packages/erc721-watcher/README.md b/packages/erc721-watcher/README.md deleted file mode 100644 index 797a55e0..00000000 --- a/packages/erc721-watcher/README.md +++ /dev/null @@ -1,305 +0,0 @@ -# erc721-watcher - -First try the [erc721 demo in stack orchestrator](https://github.com/cerc-io/stack-orchestrator/tree/main/app/data/stacks/erc721) to quickly get started. Advanced users can see [here](/docs/README.md) for instructions on setting up a local environment by hand. - -## Setup - -Run the following command to install required packages: - -```bash -yarn && yarn build -``` - -If the watcher is "active", first run the job-runner: - -```bash -yarn job-runner -``` - -then run the watcher: - -```bash -yarn server -``` - -For "lazy" watchers, you only need to run the above command. - - -Deploy an ERC721 token: - -```bash -yarn nft:deploy -``` -``` -# NFT deployed to: 0xNFTAddress -``` -Export the address of the deployed token to a shell variable for later use: - -```bash -export NFT_ADDRESS="0xNFTAddress" - ``` - -Run the following GQL mutation in generated watcher GraphQL endpoint http://127.0.0.1:3006/graphql - -```graphql -mutation { - watchContract( - address: "0xNFTAddress" - kind: "ERC721" - checkpoint: true - ) -} -``` - -TODO: settle on WC (signer/primary/main...across the docs) - -Get the signer (primary/main) account address and export to a shell variable: - -```bash -yarn account -``` - -```bash -export SIGNER_ADDRESS="0xSignerAddress" -``` - -Connect MetaMask to `http://localhost:8545` (with chain ID `99`) - -Add a an account to Metamask and export the account address to a shell variable for later use: - -```bash -export RECIPIENT_ADDRESS="0xRecipientAddress" -``` - -To get the current block hash at any time, run: - -```bash -yarn block:latest -``` - -Run the following GQL query (`eth_call`) in the GraphQL playground at http://127.0.0.1:3006/graphql - -```graphql -query { - name( - blockHash: "LATEST_BLOCK_HASH" - contractAddress: "0xNFTAddress" - ) { - value - proof { - data - } - } - symbol( - blockHash: "LATEST_BLOCK_HASH" - contractAddress: "0xNFTAddress" - ) { - value - proof { - data - } - } - balanceOf( - blockHash: "LATEST_BLOCK_HASH" - contractAddress: "0xNFTAddress" - owner: "0xSignerAddress" - ) { - value - proof { - data - } - } -} -``` - -Run the following GQL query (`storage`) in generated watcher GraphQL endpoint http://127.0.0.1:3006/graphql - -```graphql -query { - _name( - blockHash: "LATEST_BLOCK_HASH" - contractAddress: "0xNFTAddress" - ) { - value - proof { - data - } - } - _symbol( - blockHash: "LATEST_BLOCK_HASH" - contractAddress: "0xNFTAddress" - ) { - value - proof { - data - } - } - _balances( - blockHash: "LATEST_BLOCK_HASH" - contractAddress: "0xNFTAddress" - key0: "0xSignerAddress" - ) { - value - proof { - data - } - } -} -``` - -Run the following GQL subscription in the playground: - -```graphql -subscription { - onEvent { - event { - __typename - ... on TransferEvent { - from - to - tokenId - }, - ... on ApprovalEvent { - owner - approved - tokenId - } - }, - block { - number - hash - } - } -} -``` - -Mint token - -```bash -yarn nft:mint --nft $NFT_ADDRESS --to $SIGNER_ADDRESS --token-id 1 -``` - -- A Transfer event to 0xSignerAddress should be visible in the subscription. - -- An auto-generated `diff_staged` `State` should be added with parent CID pointing to the initial `checkpoint` `State`. - -- Custom property `transferCount` should be 1 initially. - -- Run the `getState` query at the endpoint to get the latest `State` for 0xNFTAddress: - -```graphql -query { - getState ( - blockHash: "EVENT_BLOCK_HASH" - contractAddress: "0xNFTAddress" - # kind: "checkpoint" - # kind: "diff" - kind: "diff_staged" - ) { - cid - block { - cid - hash - number - timestamp - parentHash - } - contractAddress - data - } -} -``` - -- `diff` States get created corresponding to the `diff_staged` blocks when their respective eth_blocks reach the pruned region. - -- `data` contains the default state and also the custom state property `transferCount` that is indexed in [hooks.ts](./src/hooks.ts) file. - -- Get the latest blockHash and run the following query for `transferCount` entity: - -```graphql -query { - transferCount( - block: { - hash: "LATEST_BLOCK_HASH" - } - id: "0xNFTAddress" - ) { - id - count - } -} -``` - -*Note: Contract address is assigned to the Entity ID.* - -With the latest blockHash, run the following query for `balanceOf` and `ownerOf` (`eth_call`): - -```graphql -query { - fromBalanceOf: balanceOf( - blockHash: "LATEST_BLOCK_HASH" - contractAddress: "0xNFTAddress" - owner: "0xSignerAddress" - ) { - value - proof { - data - } - } - toBalanceOf: balanceOf( - blockHash: "LATEST_BLOCK_HASH" - contractAddress: "0xNFTAddress" - owner: "0xRecipientAddress" - ) { - value - proof { - data - } - } - ownerOf( - blockHash: "LATEST_BLOCK_HASH" - contractAddress: "0xNFTAddress" - tokenId: 1 - ) { - value - proof { - data - } - } -} -``` - -Transfer token - -```bash -yarn nft:transfer --nft $NFT_ADDRESS --from $SIGNER_ADDRESS --to $RECIPIENT_ADDRESS --token-id 1 -``` - -- An Approval event for SIGNER_ADDRESS shall be visible in the subscription at endpoint. - -- A Transfer event to $RECIPIENT_ADDRESS shall be visible in the subscription at endpoint. - -- An auto-generated `diff_staged` State should be added with parent CID pointing to the previous State. - -- Custom property `transferCount` should be incremented after transfer. This can be checked in the `getState` query. - -- Get the latest blockHash and replace the blockHash in the above `eth_call` query. The result should be different and the token should be transferred to the recipient. - -- Run the `getState` query again at the endpoint with the event blockHash. - -- Run the `transferCount` entity query again with the latest blockHash. The updated count should be returned. - -- After the `diff` block has been created (can check if event block number pruned in yarn server log), create a checkpoint using CLI in `packages/erc721-watcher`: - -```bash -yarn checkpoint create --address $NFT_ADDRESS -``` - -- Run the `getState` query again with the output blockHash and kind `checkpoint` at the endpoint. - -- The latest checkpoint should have the aggregate of state diffs since the last checkpoint. - - The `State` entries can be seen in pg-admin in table `state`. - -- The state should have auto indexed data and also custom property `transferCount` according to code in [hooks](./src/hooks.ts) file `handleEvent` method. - -For more `yarn` sub-commands available, see the [CLI guide](/docs/cli.md) diff --git a/packages/erc721-watcher/environments/local.toml b/packages/erc721-watcher/environments/local.toml deleted file mode 100644 index 4191218d..00000000 --- a/packages/erc721-watcher/environments/local.toml +++ /dev/null @@ -1,55 +0,0 @@ -[server] - host = "127.0.0.1" - port = 3006 - kind = "active" - - # Checkpointing state. - checkpointing = true - - # Checkpoint interval in number of blocks. - checkpointInterval = 2000 - - # Enable state creation - enableState = true - - # Boolean to filter logs by contract. - filterLogs = false - - # Max block range for which to return events in eventsInRange GQL query. - # Use -1 for skipping check on block range. - maxEventsBlockRange = 1000 - -[metrics] - host = "127.0.0.1" - port = 9000 - [metrics.gql] - port = 9001 - -[database] - type = "postgres" - host = "localhost" - port = 5432 - database = "erc721-watcher" - username = "postgres" - password = "postgres" - synchronize = true - logging = false - -[upstream] - [upstream.ethServer] - gqlApiEndpoint = "http://127.0.0.1:8082/graphql" - rpcProviderEndpoint = "http://127.0.0.1:8081" - - [upstream.cache] - name = "requests" - enabled = false - deleteOnStart = false - -[jobQueue] - dbConnectionString = "postgres://postgres:postgres@localhost/erc721-watcher-job-queue" - maxCompletionLagInSecs = 300 - jobDelayInMilliSecs = 100 - eventsInBatch = 50 - blockDelayInMilliSecs = 2000 - prefetchBlocksInMem = true - prefetchBlockCount = 10 diff --git a/packages/erc721-watcher/hardhat.config.ts b/packages/erc721-watcher/hardhat.config.ts deleted file mode 100644 index 69ee1e0d..00000000 --- a/packages/erc721-watcher/hardhat.config.ts +++ /dev/null @@ -1,29 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import '@nomiclabs/hardhat-waffle'; - -import './test/tasks/nft-deploy'; -import './test/tasks/nft-mint'; -import './test/tasks/nft-transfer'; -import './test/tasks/block-latest'; -import './test/tasks/account'; - -// You need to export an object to set up your config -// Go to https://hardhat.org/config/ to learn more - -/** - * @type import('hardhat/config').HardhatUserConfig - */ -export default { - solidity: '0.8.1', - networks: { - docker: { - url: process.env.ETH_RPC_URL - } - }, - paths: { - sources: './test/contracts' - } -}; diff --git a/packages/erc721-watcher/package.json b/packages/erc721-watcher/package.json deleted file mode 100644 index bc82ea15..00000000 --- a/packages/erc721-watcher/package.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "name": "@cerc-io/erc721-watcher", - "version": "0.2.38", - "description": "erc721-watcher", - "private": true, - "main": "dist/index.js", - "scripts": { - "lint": "eslint .", - "build": "yarn clean && tsc && yarn copy-assets", - "clean": "rm -rf ./dist", - "copy-assets": "copyfiles -u 1 src/**/*.gql dist/", - "server": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true node --enable-source-maps dist/server.js", - "server:dev": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true ts-node src/server.ts", - "job-runner": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true node --enable-source-maps dist/job-runner.js", - "job-runner:dev": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true ts-node src/job-runner.ts", - "watch:contract": "DEBUG=vulcanize:* ts-node src/cli/watch-contract.ts", - "fill": "DEBUG=vulcanize:* ts-node src/fill.ts", - "reset": "DEBUG=vulcanize:* ts-node src/cli/reset.ts", - "checkpoint": "DEBUG=vulcanize:* node --enable-source-maps dist/cli/checkpoint.js", - "checkpoint:dev": "DEBUG=vulcanize:* ts-node src/cli/checkpoint.ts", - "export-state": "DEBUG=vulcanize:* node --enable-source-maps dist/cli/export-state.js", - "export-state:dev": "DEBUG=vulcanize:* ts-node src/cli/export-state.ts", - "import-state": "DEBUG=vulcanize:* node --enable-source-maps dist/cli/import-state.js", - "import-state:dev": "DEBUG=vulcanize:* ts-node src/cli/import-state.ts", - "inspect-cid": "DEBUG=vulcanize:* ts-node src/cli/inspect-cid.ts", - "index-block": "DEBUG=vulcanize:* ts-node src/cli/index-block.ts", - "nft:deploy": "hardhat --network localhost nft-deploy", - "nft:deploy:docker": "hardhat --network docker nft-deploy", - "nft:mint": "hardhat --network localhost nft-mint", - "nft:mint:docker": "hardhat --network docker nft-mint", - "nft:transfer": "hardhat --network localhost nft-transfer", - "nft:transfer:docker": "hardhat --network docker nft-transfer", - "block:latest": "hardhat --network localhost block-latest", - "block:latest:docker": "hardhat --network docker block-latest", - "account": "hardhat --network localhost account", - "account:docker": "hardhat --network docker account" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/cerc-io/watcher-ts.git" - }, - "author": "", - "license": "AGPL-3.0", - "bugs": { - "url": "https://github.com/cerc-io/watcher-ts/issues" - }, - "homepage": "https://github.com/cerc-io/watcher-ts#readme", - "dependencies": { - "@apollo/client": "^3.3.19", - "@cerc-io/cli": "^0.2.38", - "@cerc-io/ipld-eth-client": "^0.2.38", - "@cerc-io/solidity-mapper": "^0.2.38", - "@cerc-io/util": "^0.2.38", - "@ethersproject/providers": "^5.4.4", - "apollo-type-bigint": "^0.1.3", - "debug": "^4.3.1", - "decimal.js": "^10.3.1", - "ethers": "^5.4.4", - "graphql": "^15.5.0", - "json-bigint": "^1.0.0", - "reflect-metadata": "^0.1.13", - "typeorm": "^0.2.32", - "yargs": "^17.0.1" - }, - "devDependencies": { - "@ethersproject/abi": "^5.3.0", - "@nomiclabs/hardhat-ethers": "^2.0.2", - "@nomiclabs/hardhat-waffle": "^2.0.1", - "@openzeppelin/contracts": "^4.3.2", - "@types/yargs": "^17.0.0", - "@typescript-eslint/eslint-plugin": "^5.47.1", - "@typescript-eslint/parser": "^5.47.1", - "copyfiles": "^2.4.1", - "eslint": "^8.35.0", - "eslint-config-semistandard": "^15.0.1", - "eslint-config-standard": "^16.0.3", - "eslint-plugin-import": "^2.27.5", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-promise": "^5.1.0", - "eslint-plugin-standard": "^5.0.0", - "hardhat": "^2.3.0", - "ts-node": "^10.2.1", - "typescript": "^5.0.2" - } -} diff --git a/packages/erc721-watcher/src/artifacts/ERC721.json b/packages/erc721-watcher/src/artifacts/ERC721.json deleted file mode 100644 index ebebbd41..00000000 --- a/packages/erc721-watcher/src/artifacts/ERC721.json +++ /dev/null @@ -1,452 +0,0 @@ -{ - "abi": [ - { - "inputs": [ - { - "internalType": "string", - "name": "name_", - "type": "string" - }, - { - "internalType": "string", - "name": "symbol_", - "type": "string" - } - ], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "approved", - "type": "address" - }, - { - "indexed": true, - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - } - ], - "name": "Approval", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "operator", - "type": "address" - }, - { - "indexed": false, - "internalType": "bool", - "name": "approved", - "type": "bool" - } - ], - "name": "ApprovalForAll", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "from", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "indexed": true, - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - } - ], - "name": "Transfer", - "type": "event" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - } - ], - "name": "approve", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "owner", - "type": "address" - } - ], - "name": "balanceOf", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - } - ], - "name": "getApproved", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "internalType": "address", - "name": "operator", - "type": "address" - } - ], - "name": "isApprovedForAll", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "name", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - } - ], - "name": "ownerOf", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "from", - "type": "address" - }, - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - } - ], - "name": "safeTransferFrom", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "from", - "type": "address" - }, - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "_data", - "type": "bytes" - } - ], - "name": "safeTransferFrom", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "operator", - "type": "address" - }, - { - "internalType": "bool", - "name": "approved", - "type": "bool" - } - ], - "name": "setApprovalForAll", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes4", - "name": "interfaceId", - "type": "bytes4" - } - ], - "name": "supportsInterface", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "symbol", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - } - ], - "name": "tokenURI", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "from", - "type": "address" - }, - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "tokenId", - "type": "uint256" - } - ], - "name": "transferFrom", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - } - ], - "storageLayout": { - "storage": [ - { - "astId": 718, - "contract": "ERC721.sol:ERC721", - "label": "_name", - "offset": 0, - "slot": "0", - "type": "t_string_storage" - }, - { - "astId": 720, - "contract": "ERC721.sol:ERC721", - "label": "_symbol", - "offset": 0, - "slot": "1", - "type": "t_string_storage" - }, - { - "astId": 724, - "contract": "ERC721.sol:ERC721", - "label": "_owners", - "offset": 0, - "slot": "2", - "type": "t_mapping(t_uint256,t_address)" - }, - { - "astId": 728, - "contract": "ERC721.sol:ERC721", - "label": "_balances", - "offset": 0, - "slot": "3", - "type": "t_mapping(t_address,t_uint256)" - }, - { - "astId": 732, - "contract": "ERC721.sol:ERC721", - "label": "_tokenApprovals", - "offset": 0, - "slot": "4", - "type": "t_mapping(t_uint256,t_address)" - }, - { - "astId": 738, - "contract": "ERC721.sol:ERC721", - "label": "_operatorApprovals", - "offset": 0, - "slot": "5", - "type": "t_mapping(t_address,t_mapping(t_address,t_bool))" - } - ], - "types": { - "t_address": { - "encoding": "inplace", - "label": "address", - "numberOfBytes": "20" - }, - "t_bool": { - "encoding": "inplace", - "label": "bool", - "numberOfBytes": "1" - }, - "t_mapping(t_address,t_bool)": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => bool)", - "numberOfBytes": "32", - "value": "t_bool" - }, - "t_mapping(t_address,t_mapping(t_address,t_bool))": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => mapping(address => bool))", - "numberOfBytes": "32", - "value": "t_mapping(t_address,t_bool)" - }, - "t_mapping(t_address,t_uint256)": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => uint256)", - "numberOfBytes": "32", - "value": "t_uint256" - }, - "t_mapping(t_uint256,t_address)": { - "encoding": "mapping", - "key": "t_uint256", - "label": "mapping(uint256 => address)", - "numberOfBytes": "32", - "value": "t_address" - }, - "t_string_storage": { - "encoding": "bytes", - "label": "string", - "numberOfBytes": "32" - }, - "t_uint256": { - "encoding": "inplace", - "label": "uint256", - "numberOfBytes": "32" - } - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/cli/checkpoint-cmds/create.ts b/packages/erc721-watcher/src/cli/checkpoint-cmds/create.ts deleted file mode 100644 index 01408fe5..00000000 --- a/packages/erc721-watcher/src/cli/checkpoint-cmds/create.ts +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { CreateCheckpointCmd } from '@cerc-io/cli'; - -import { Database } from '../../database'; -import { Indexer } from '../../indexer'; - -export const command = 'create'; - -export const desc = 'Create checkpoint'; - -export const builder = { - address: { - type: 'string', - require: true, - demandOption: true, - describe: 'Contract address to create the checkpoint for.' - }, - blockHash: { - type: 'string', - describe: 'Blockhash at which to create the checkpoint.' - } -}; - -export const handler = async (argv: any): Promise => { - const createCheckpointCmd = new CreateCheckpointCmd(); - await createCheckpointCmd.init(argv, Database); - await createCheckpointCmd.initIndexer(Indexer); - - await createCheckpointCmd.exec(); -}; diff --git a/packages/erc721-watcher/src/cli/checkpoint.ts b/packages/erc721-watcher/src/cli/checkpoint.ts deleted file mode 100644 index d05ad8ad..00000000 --- a/packages/erc721-watcher/src/cli/checkpoint.ts +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import yargs from 'yargs'; -import 'reflect-metadata'; -import debug from 'debug'; - -import { DEFAULT_CONFIG_PATH } from '@cerc-io/util'; - -import { hideBin } from 'yargs/helpers'; - -const log = debug('vulcanize:checkpoint'); - -const main = async () => { - return yargs(hideBin(process.argv)) - .parserConfiguration({ - 'parse-numbers': false - }).options({ - configFile: { - alias: 'f', - type: 'string', - require: true, - demandOption: true, - describe: 'configuration file path (toml)', - default: DEFAULT_CONFIG_PATH - } - }) - .commandDir('checkpoint-cmds', { extensions: ['ts', 'js'], exclude: /([a-zA-Z0-9\s_\\.\-:])+(.d.ts)$/ }) - .demandCommand(1) - .help() - .argv; -}; - -main().then(() => { - process.exit(); -}).catch(err => { - log(err); -}); diff --git a/packages/erc721-watcher/src/cli/export-state.ts b/packages/erc721-watcher/src/cli/export-state.ts deleted file mode 100644 index d0ae922d..00000000 --- a/packages/erc721-watcher/src/cli/export-state.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { ExportStateCmd } from '@cerc-io/cli'; - -import { Database } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:export-state'); - -const main = async (): Promise => { - const exportStateCmd = new ExportStateCmd(); - await exportStateCmd.init(Database); - await exportStateCmd.initIndexer(Indexer); - - await exportStateCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/erc721-watcher/src/cli/import-state.ts b/packages/erc721-watcher/src/cli/import-state.ts deleted file mode 100644 index 79771fcd..00000000 --- a/packages/erc721-watcher/src/cli/import-state.ts +++ /dev/null @@ -1,28 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { ImportStateCmd } from '@cerc-io/cli'; - -import { Database } from '../database'; -import { Indexer } from '../indexer'; -import { State } from '../entity/State'; - -const log = debug('vulcanize:import-state'); - -export const main = async (): Promise => { - const importStateCmd = new ImportStateCmd(); - await importStateCmd.init(Database); - await importStateCmd.initIndexer(Indexer); - - await importStateCmd.exec(State); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/erc721-watcher/src/cli/index-block.ts b/packages/erc721-watcher/src/cli/index-block.ts deleted file mode 100644 index 4ebad2a0..00000000 --- a/packages/erc721-watcher/src/cli/index-block.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { IndexBlockCmd } from '@cerc-io/cli'; - -import { Database } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:index-block'); - -const main = async (): Promise => { - const indexBlockCmd = new IndexBlockCmd(); - await indexBlockCmd.init(Database); - await indexBlockCmd.initIndexer(Indexer); - - await indexBlockCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/erc721-watcher/src/cli/inspect-cid.ts b/packages/erc721-watcher/src/cli/inspect-cid.ts deleted file mode 100644 index 740cfdf3..00000000 --- a/packages/erc721-watcher/src/cli/inspect-cid.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { InspectCIDCmd } from '@cerc-io/cli'; - -import { Database } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:inspect-cid'); - -const main = async (): Promise => { - const inspectCIDCmd = new InspectCIDCmd(); - await inspectCIDCmd.init(Database); - await inspectCIDCmd.initIndexer(Indexer); - - await inspectCIDCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/erc721-watcher/src/cli/reset-cmds/job-queue.ts b/packages/erc721-watcher/src/cli/reset-cmds/job-queue.ts deleted file mode 100644 index c33cbfd6..00000000 --- a/packages/erc721-watcher/src/cli/reset-cmds/job-queue.ts +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import debug from 'debug'; - -import { getConfig, resetJobs, Config } from '@cerc-io/util'; - -const log = debug('vulcanize:reset-job-queue'); - -export const command = 'job-queue'; - -export const desc = 'Reset job queue'; - -export const builder = {}; - -export const handler = async (argv: any): Promise => { - const config: Config = await getConfig(argv.configFile); - await resetJobs(config); - - log('Job queue reset successfully'); -}; diff --git a/packages/erc721-watcher/src/cli/reset-cmds/state.ts b/packages/erc721-watcher/src/cli/reset-cmds/state.ts deleted file mode 100644 index 33211d6e..00000000 --- a/packages/erc721-watcher/src/cli/reset-cmds/state.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { ResetStateCmd } from '@cerc-io/cli'; - -import { Database } from '../../database'; - -export const command = 'state'; - -export const desc = 'Reset State to a given block number'; - -export const builder = { - blockNumber: { - type: 'number' - } -}; - -export const handler = async (argv: any): Promise => { - const resetStateCmd = new ResetStateCmd(); - await resetStateCmd.init(argv, Database); - - await resetStateCmd.exec(); -}; diff --git a/packages/erc721-watcher/src/cli/reset-cmds/watcher.ts b/packages/erc721-watcher/src/cli/reset-cmds/watcher.ts deleted file mode 100644 index c6e651f5..00000000 --- a/packages/erc721-watcher/src/cli/reset-cmds/watcher.ts +++ /dev/null @@ -1,26 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { ResetWatcherCmd } from '@cerc-io/cli'; - -import { Database } from '../../database'; -import { Indexer } from '../../indexer'; - -export const command = 'watcher'; - -export const desc = 'Reset watcher to a block number'; - -export const builder = { - blockNumber: { - type: 'number' - } -}; - -export const handler = async (argv: any): Promise => { - const resetWatcherCmd = new ResetWatcherCmd(); - await resetWatcherCmd.init(argv, Database); - await resetWatcherCmd.initIndexer(Indexer); - - await resetWatcherCmd.exec(); -}; diff --git a/packages/erc721-watcher/src/cli/reset.ts b/packages/erc721-watcher/src/cli/reset.ts deleted file mode 100644 index 95648c88..00000000 --- a/packages/erc721-watcher/src/cli/reset.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { getResetYargs } from '@cerc-io/util'; - -const log = debug('vulcanize:reset'); - -const main = async () => { - return getResetYargs() - .commandDir('reset-cmds', { extensions: ['ts', 'js'], exclude: /([a-zA-Z0-9\s_\\.\-:])+(.d.ts)$/ }) - .demandCommand(1) - .help() - .argv; -}; - -main().then(() => { - process.exit(); -}).catch(err => { - log(err); -}); diff --git a/packages/erc721-watcher/src/cli/watch-contract.ts b/packages/erc721-watcher/src/cli/watch-contract.ts deleted file mode 100644 index b68568e7..00000000 --- a/packages/erc721-watcher/src/cli/watch-contract.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { WatchContractCmd } from '@cerc-io/cli'; - -import { Database } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:watch-contract'); - -const main = async (): Promise => { - const watchContractCmd = new WatchContractCmd(); - await watchContractCmd.init(Database); - await watchContractCmd.initIndexer(Indexer); - - await watchContractCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/erc721-watcher/src/client.ts b/packages/erc721-watcher/src/client.ts deleted file mode 100644 index 986e707f..00000000 --- a/packages/erc721-watcher/src/client.ts +++ /dev/null @@ -1,181 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { gql } from '@apollo/client/core'; -import { GraphQLClient, GraphQLConfig } from '@cerc-io/ipld-eth-client'; - -import { queries, mutations, subscriptions } from './gql'; - -export class Client { - _config: GraphQLConfig; - _client: GraphQLClient; - - constructor (config: GraphQLConfig) { - this._config = config; - - this._client = new GraphQLClient(config); - } - - async getSupportsInterface (blockHash: string, contractAddress: string, interfaceId: string): Promise { - const { supportsInterface } = await this._client.query( - gql(queries.supportsInterface), - { blockHash, contractAddress, interfaceId } - ); - - return supportsInterface; - } - - async getBalanceOf (blockHash: string, contractAddress: string, owner: string): Promise { - const { balanceOf } = await this._client.query( - gql(queries.balanceOf), - { blockHash, contractAddress, owner } - ); - - return balanceOf; - } - - async getOwnerOf (blockHash: string, contractAddress: string, tokenId: bigint): Promise { - const { ownerOf } = await this._client.query( - gql(queries.ownerOf), - { blockHash, contractAddress, tokenId } - ); - - return ownerOf; - } - - async getGetApproved (blockHash: string, contractAddress: string, tokenId: bigint): Promise { - const { getApproved } = await this._client.query( - gql(queries.getApproved), - { blockHash, contractAddress, tokenId } - ); - - return getApproved; - } - - async getIsApprovedForAll (blockHash: string, contractAddress: string, owner: string, operator: string): Promise { - const { isApprovedForAll } = await this._client.query( - gql(queries.isApprovedForAll), - { blockHash, contractAddress, owner, operator } - ); - - return isApprovedForAll; - } - - async getName (blockHash: string, contractAddress: string): Promise { - const { name } = await this._client.query( - gql(queries.name), - { blockHash, contractAddress } - ); - - return name; - } - - async getSymbol (blockHash: string, contractAddress: string): Promise { - const { symbol } = await this._client.query( - gql(queries.symbol), - { blockHash, contractAddress } - ); - - return symbol; - } - - async getTokenURI (blockHash: string, contractAddress: string, tokenId: bigint): Promise { - const { tokenURI } = await this._client.query( - gql(queries.tokenURI), - { blockHash, contractAddress, tokenId } - ); - - return tokenURI; - } - - async _getName (blockHash: string, contractAddress: string): Promise { - const { _name } = await this._client.query( - gql(queries._name), - { blockHash, contractAddress } - ); - - return _name; - } - - async _getSymbol (blockHash: string, contractAddress: string): Promise { - const { _symbol } = await this._client.query( - gql(queries._symbol), - { blockHash, contractAddress } - ); - - return _symbol; - } - - async _getOwners (blockHash: string, contractAddress: string, key0: bigint): Promise { - const { _owners } = await this._client.query( - gql(queries._owners), - { blockHash, contractAddress, key0 } - ); - - return _owners; - } - - async _getBalances (blockHash: string, contractAddress: string, key0: string): Promise { - const { _balances } = await this._client.query( - gql(queries._balances), - { blockHash, contractAddress, key0 } - ); - - return _balances; - } - - async _getTokenApprovals (blockHash: string, contractAddress: string, key0: bigint): Promise { - const { _tokenApprovals } = await this._client.query( - gql(queries._tokenApprovals), - { blockHash, contractAddress, key0 } - ); - - return _tokenApprovals; - } - - async _getOperatorApprovals (blockHash: string, contractAddress: string, key0: string, key1: string): Promise { - const { _operatorApprovals } = await this._client.query( - gql(queries._operatorApprovals), - { blockHash, contractAddress, key0, key1 } - ); - - return _operatorApprovals; - } - - async getEvents (blockHash: string, contractAddress: string, name: string): Promise { - const { events } = await this._client.query( - gql(queries.events), - { blockHash, contractAddress, name } - ); - - return events; - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise { - const { eventsInRange } = await this._client.query( - gql(queries.eventsInRange), - { fromBlockNumber, toBlockNumber } - ); - - return eventsInRange; - } - - async watchContract (contractAddress: string, startingBlock?: number): Promise { - const { watchContract } = await this._client.mutate( - gql(mutations.watchContract), - { contractAddress, startingBlock } - ); - - return watchContract; - } - - async watchEvents (onNext: (value: any) => void): Promise { - return this._client.subscribe( - gql(subscriptions.onEvent), - ({ data }) => { - onNext(data.onEvent); - } - ); - } -} diff --git a/packages/erc721-watcher/src/database.ts b/packages/erc721-watcher/src/database.ts deleted file mode 100644 index 1db748ac..00000000 --- a/packages/erc721-watcher/src/database.ts +++ /dev/null @@ -1,538 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import { Connection, ConnectionOptions, DeepPartial, FindConditions, QueryRunner, FindManyOptions, FindOneOptions, LessThanOrEqual, EntityTarget, UpdateResult } from 'typeorm'; -import path from 'path'; - -import { Database as BaseDatabase, DatabaseInterface, QueryOptions, StateKind, Where } from '@cerc-io/util'; - -import { Contract } from './entity/Contract'; -import { Event } from './entity/Event'; -import { SyncStatus } from './entity/SyncStatus'; -import { StateSyncStatus } from './entity/StateSyncStatus'; -import { BlockProgress } from './entity/BlockProgress'; -import { State } from './entity/State'; -import { SupportsInterface } from './entity/SupportsInterface'; -import { BalanceOf } from './entity/BalanceOf'; -import { OwnerOf } from './entity/OwnerOf'; -import { GetApproved } from './entity/GetApproved'; -import { IsApprovedForAll } from './entity/IsApprovedForAll'; -import { Name } from './entity/Name'; -import { Symbol } from './entity/Symbol'; -import { TokenURI } from './entity/TokenURI'; -import { _Name } from './entity/_Name'; -import { _Symbol } from './entity/_Symbol'; -import { _Owners } from './entity/_Owners'; -import { _Balances } from './entity/_Balances'; -import { _TokenApprovals } from './entity/_TokenApprovals'; -import { _OperatorApprovals } from './entity/_OperatorApprovals'; -import { TransferCount } from './entity/TransferCount'; - -export const ENTITIES = [_Balances, _Name, _OperatorApprovals, _Owners, _Symbol, _TokenApprovals, BalanceOf, GetApproved, IsApprovedForAll, Name, OwnerOf, SupportsInterface, Symbol, TokenURI, TransferCount]; - -export class Database implements DatabaseInterface { - _config: ConnectionOptions; - _conn!: Connection; - _baseDatabase: BaseDatabase; - _propColMaps: { [key: string]: Map; }; - - constructor (config: ConnectionOptions) { - assert(config); - - this._config = { - ...config, - entities: [path.join(__dirname, 'entity/*')] - }; - - this._baseDatabase = new BaseDatabase(this._config); - this._propColMaps = {}; - } - - get baseDatabase (): BaseDatabase { - return this._baseDatabase; - } - - async init (): Promise { - this._conn = await this._baseDatabase.init(); - this._setPropColMaps(); - } - - async close (): Promise { - return this._baseDatabase.close(); - } - - async getSupportsInterface ({ blockHash, contractAddress, interfaceId }: { blockHash: string, contractAddress: string, interfaceId: string }): Promise { - return this._conn.getRepository(SupportsInterface) - .findOne({ - blockHash, - contractAddress, - interfaceId - }); - } - - async getBalanceOf ({ blockHash, contractAddress, owner }: { blockHash: string, contractAddress: string, owner: string }): Promise { - return this._conn.getRepository(BalanceOf) - .findOne({ - blockHash, - contractAddress, - owner - }); - } - - async getOwnerOf ({ blockHash, contractAddress, tokenId }: { blockHash: string, contractAddress: string, tokenId: bigint }): Promise { - return this._conn.getRepository(OwnerOf) - .findOne({ - blockHash, - contractAddress, - tokenId - }); - } - - async getGetApproved ({ blockHash, contractAddress, tokenId }: { blockHash: string, contractAddress: string, tokenId: bigint }): Promise { - return this._conn.getRepository(GetApproved) - .findOne({ - blockHash, - contractAddress, - tokenId - }); - } - - async getIsApprovedForAll ({ blockHash, contractAddress, owner, operator }: { blockHash: string, contractAddress: string, owner: string, operator: string }): Promise { - return this._conn.getRepository(IsApprovedForAll) - .findOne({ - blockHash, - contractAddress, - owner, - operator - }); - } - - async getName ({ blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise { - return this._conn.getRepository(Name) - .findOne({ - blockHash, - contractAddress - }); - } - - // eslint-disable-next-line @typescript-eslint/ban-types - async getSymbol ({ blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise { - return this._conn.getRepository(Symbol) - .findOne({ - blockHash, - contractAddress - }); - } - - async getTokenURI ({ blockHash, contractAddress, tokenId }: { blockHash: string, contractAddress: string, tokenId: bigint }): Promise { - return this._conn.getRepository(TokenURI) - .findOne({ - blockHash, - contractAddress, - tokenId - }); - } - - async getTransferCount (queryRunner: QueryRunner, { id, blockHash, blockNumber }: DeepPartial): Promise { - const repo = queryRunner.manager.getRepository(TransferCount); - const whereOptions: FindConditions = { id }; - - if (blockHash) { - whereOptions.blockHash = blockHash; - } - - if (blockNumber) { - whereOptions.blockNumber = LessThanOrEqual(blockNumber); - } - - const findOptions = { - where: whereOptions, - order: { - blockNumber: 'DESC' - } - }; - - let entity = await repo.findOne(findOptions as FindOneOptions); - - if (!entity && findOptions.where.blockHash) { - entity = await this._baseDatabase.getPrevEntityVersion(queryRunner, repo, findOptions); - } - - return entity; - } - - async saveTransferCount (queryRunner: QueryRunner, transferCount: TransferCount): Promise { - const repo = queryRunner.manager.getRepository(TransferCount); - return repo.save(transferCount); - } - - async _getName ({ blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise<_Name | undefined> { - return this._conn.getRepository(_Name) - .findOne({ - blockHash, - contractAddress - }); - } - - async _getSymbol ({ blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise<_Symbol | undefined> { - return this._conn.getRepository(_Symbol) - .findOne({ - blockHash, - contractAddress - }); - } - - async _getOwners ({ blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: bigint }): Promise<_Owners | undefined> { - return this._conn.getRepository(_Owners) - .findOne({ - blockHash, - contractAddress, - key0 - }); - } - - async _getBalances ({ blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: string }): Promise<_Balances | undefined> { - return this._conn.getRepository(_Balances) - .findOne({ - blockHash, - contractAddress, - key0 - }); - } - - async _getTokenApprovals ({ blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: bigint }): Promise<_TokenApprovals | undefined> { - return this._conn.getRepository(_TokenApprovals) - .findOne({ - blockHash, - contractAddress, - key0 - }); - } - - async _getOperatorApprovals ({ blockHash, contractAddress, key0, key1 }: { blockHash: string, contractAddress: string, key0: string, key1: string }): Promise<_OperatorApprovals | undefined> { - return this._conn.getRepository(_OperatorApprovals) - .findOne({ - blockHash, - contractAddress, - key0, - key1 - }); - } - - async saveSupportsInterface ({ blockHash, blockNumber, contractAddress, interfaceId, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(SupportsInterface); - const entity = repo.create({ blockHash, blockNumber, contractAddress, interfaceId, value, proof }); - return repo.save(entity); - } - - async saveBalanceOf ({ blockHash, blockNumber, contractAddress, owner, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(BalanceOf); - const entity = repo.create({ blockHash, blockNumber, contractAddress, owner, value, proof }); - return repo.save(entity); - } - - async saveOwnerOf ({ blockHash, blockNumber, contractAddress, tokenId, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(OwnerOf); - const entity = repo.create({ blockHash, blockNumber, contractAddress, tokenId, value, proof }); - return repo.save(entity); - } - - async saveGetApproved ({ blockHash, blockNumber, contractAddress, tokenId, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(GetApproved); - const entity = repo.create({ blockHash, blockNumber, contractAddress, tokenId, value, proof }); - return repo.save(entity); - } - - async saveIsApprovedForAll ({ blockHash, blockNumber, contractAddress, owner, operator, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(IsApprovedForAll); - const entity = repo.create({ blockHash, blockNumber, contractAddress, owner, operator, value, proof }); - return repo.save(entity); - } - - async saveName ({ blockHash, blockNumber, contractAddress, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(Name); - const entity = repo.create({ blockHash, blockNumber, contractAddress, value, proof }); - return repo.save(entity); - } - - // eslint-disable-next-line @typescript-eslint/ban-types - async saveSymbol ({ blockHash, blockNumber, contractAddress, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(Symbol); - const entity = repo.create({ blockHash, blockNumber, contractAddress, value, proof }); - return repo.save(entity); - } - - async saveTokenURI ({ blockHash, blockNumber, contractAddress, tokenId, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(TokenURI); - const entity = repo.create({ blockHash, blockNumber, contractAddress, tokenId, value, proof }); - return repo.save(entity); - } - - async _saveName ({ blockHash, blockNumber, contractAddress, value, proof }: DeepPartial<_Name>): Promise<_Name> { - const repo = this._conn.getRepository(_Name); - const entity = repo.create({ blockHash, blockNumber, contractAddress, value, proof }); - return repo.save(entity); - } - - async _saveSymbol ({ blockHash, blockNumber, contractAddress, value, proof }: DeepPartial<_Symbol>): Promise<_Symbol> { - const repo = this._conn.getRepository(_Symbol); - const entity = repo.create({ blockHash, blockNumber, contractAddress, value, proof }); - return repo.save(entity); - } - - async _saveOwners ({ blockHash, blockNumber, contractAddress, key0, value, proof }: DeepPartial<_Owners>): Promise<_Owners> { - const repo = this._conn.getRepository(_Owners); - const entity = repo.create({ blockHash, blockNumber, contractAddress, key0, value, proof }); - return repo.save(entity); - } - - async _saveBalances ({ blockHash, blockNumber, contractAddress, key0, value, proof }: DeepPartial<_Balances>): Promise<_Balances> { - const repo = this._conn.getRepository(_Balances); - const entity = repo.create({ blockHash, blockNumber, contractAddress, key0, value, proof }); - return repo.save(entity); - } - - async _saveTokenApprovals ({ blockHash, blockNumber, contractAddress, key0, value, proof }: DeepPartial<_TokenApprovals>): Promise<_TokenApprovals> { - const repo = this._conn.getRepository(_TokenApprovals); - const entity = repo.create({ blockHash, blockNumber, contractAddress, key0, value, proof }); - return repo.save(entity); - } - - async _saveOperatorApprovals ({ blockHash, blockNumber, contractAddress, key0, key1, value, proof }: DeepPartial<_OperatorApprovals>): Promise<_OperatorApprovals> { - const repo = this._conn.getRepository(_OperatorApprovals); - const entity = repo.create({ blockHash, blockNumber, contractAddress, key0, key1, value, proof }); - return repo.save(entity); - } - - getNewState (): State { - return new State(); - } - - async getStates (where: FindConditions): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getStates(repo, where); - } - - async getLatestState (contractAddress: string, kind: StateKind | null, blockNumber?: number): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getLatestState(repo, contractAddress, kind, blockNumber); - } - - async getPrevState (blockHash: string, contractAddress: string, kind?: string): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getPrevState(repo, blockHash, contractAddress, kind); - } - - // Fetch all diff States after the specified block number. - async getDiffStatesInRange (contractAddress: string, startblock: number, endBlock: number): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getDiffStatesInRange(repo, contractAddress, startblock, endBlock); - } - - async saveOrUpdateState (dbTx: QueryRunner, state: State): Promise { - const repo = dbTx.manager.getRepository(State); - - return this._baseDatabase.saveOrUpdateState(repo, state); - } - - async removeStates (dbTx: QueryRunner, blockNumber: number, kind: string): Promise { - const repo = dbTx.manager.getRepository(State); - - await this._baseDatabase.removeStates(repo, blockNumber, kind); - } - - async removeStatesAfterBlock (dbTx: QueryRunner, blockNumber: number): Promise { - const repo = dbTx.manager.getRepository(State); - - await this._baseDatabase.removeStatesAfterBlock(repo, blockNumber); - } - - async getStateSyncStatus (): Promise { - const repo = this._conn.getRepository(StateSyncStatus); - - return this._baseDatabase.getStateSyncStatus(repo); - } - - async updateStateSyncStatusIndexedBlock (queryRunner: QueryRunner, blockNumber: number, force?: boolean): Promise { - const repo = queryRunner.manager.getRepository(StateSyncStatus); - - return this._baseDatabase.updateStateSyncStatusIndexedBlock(repo, blockNumber, force); - } - - async updateStateSyncStatusCheckpointBlock (queryRunner: QueryRunner, blockNumber: number, force?: boolean): Promise { - const repo = queryRunner.manager.getRepository(StateSyncStatus); - - return this._baseDatabase.updateStateSyncStatusCheckpointBlock(repo, blockNumber, force); - } - - async getContracts (): Promise { - const repo = this._conn.getRepository(Contract); - - return this._baseDatabase.getContracts(repo); - } - - async createTransactionRunner (): Promise { - return this._baseDatabase.createTransactionRunner(); - } - - async getProcessedBlockCountForRange (fromBlockNumber: number, toBlockNumber: number): Promise<{ expected: number, actual: number }> { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getProcessedBlockCountForRange(repo, fromBlockNumber, toBlockNumber); - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise> { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getEventsInRange(repo, fromBlockNumber, toBlockNumber); - } - - async saveEventEntity (queryRunner: QueryRunner, entity: Event): Promise { - const repo = queryRunner.manager.getRepository(Event); - return this._baseDatabase.saveEventEntity(repo, entity); - } - - async getBlockEvents (blockHash: string, where: Where, queryOptions: QueryOptions): Promise { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getBlockEvents(repo, blockHash, where, queryOptions); - } - - async saveBlockWithEvents (queryRunner: QueryRunner, block: DeepPartial, events: DeepPartial[]): Promise { - const blockRepo = queryRunner.manager.getRepository(BlockProgress); - const eventRepo = queryRunner.manager.getRepository(Event); - - return this._baseDatabase.saveBlockWithEvents(blockRepo, eventRepo, block, events); - } - - async saveEvents (queryRunner: QueryRunner, events: Event[]): Promise { - const eventRepo = queryRunner.manager.getRepository(Event); - - return this._baseDatabase.saveEvents(eventRepo, events); - } - - async saveBlockProgress (queryRunner: QueryRunner, block: DeepPartial): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.saveBlockProgress(repo, block); - } - - async saveContract (queryRunner: QueryRunner, address: string, kind: string, checkpoint: boolean, startingBlock: number): Promise { - const repo = queryRunner.manager.getRepository(Contract); - - return this._baseDatabase.saveContract(repo, address, kind, checkpoint, startingBlock); - } - - async updateSyncStatusIndexedBlock (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusIndexedBlock(repo, blockHash, blockNumber, force); - } - - async updateSyncStatusCanonicalBlock (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusCanonicalBlock(repo, blockHash, blockNumber, force); - } - - async updateSyncStatusChainHead (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusChainHead(repo, blockHash, blockNumber, force); - } - - async getSyncStatus (queryRunner: QueryRunner): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.getSyncStatus(repo); - } - - async getEvent (id: string): Promise { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getEvent(repo, id); - } - - async getBlocksAtHeight (height: number, isPruned: boolean): Promise { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getBlocksAtHeight(repo, height, isPruned); - } - - async markBlocksAsPruned (queryRunner: QueryRunner, blocks: BlockProgress[]): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.markBlocksAsPruned(repo, blocks); - } - - async getBlockProgress (blockHash: string): Promise { - const repo = this._conn.getRepository(BlockProgress); - return this._baseDatabase.getBlockProgress(repo, blockHash); - } - - async getBlockProgressEntities (where: FindConditions, options: FindManyOptions): Promise { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getBlockProgressEntities(repo, where, options); - } - - async getEntitiesForBlock (blockHash: string, tableName: string): Promise { - return this._baseDatabase.getEntitiesForBlock(blockHash, tableName); - } - - async updateBlockProgress (queryRunner: QueryRunner, block: BlockProgress, lastProcessedEventIndex: number): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.updateBlockProgress(repo, block, lastProcessedEventIndex); - } - - async removeEntities (queryRunner: QueryRunner, entity: new () => Entity, findConditions?: FindManyOptions | FindConditions): Promise { - return this._baseDatabase.removeEntities(queryRunner, entity, findConditions); - } - - async deleteEntitiesByConditions (queryRunner: QueryRunner, entity: EntityTarget, findConditions: FindConditions): Promise { - await this._baseDatabase.deleteEntitiesByConditions(queryRunner, entity, findConditions); - } - - async getAncestorAtDepth (blockHash: string, depth: number): Promise { - return this._baseDatabase.getAncestorAtDepth(blockHash, depth); - } - - async updateEntity (queryRunner: QueryRunner, entityType: new () => Entity, criteria: any, update: any): Promise { - const repo = queryRunner.manager.getRepository(entityType); - return repo.createQueryBuilder() - .update() - .set(update) - .where(criteria) - .execute(); - } - - _getPropertyColumnMapForEntity (entityName: string): Map { - return this._conn.getMetadata(entityName).ownColumns.reduce((acc, curr) => { - return acc.set(curr.propertyName, curr.databaseName); - }, new Map()); - } - - _setPropColMaps (): void { - this._propColMaps.SupportsInterface = this._getPropertyColumnMapForEntity('SupportsInterface'); - this._propColMaps.BalanceOf = this._getPropertyColumnMapForEntity('BalanceOf'); - this._propColMaps.OwnerOf = this._getPropertyColumnMapForEntity('OwnerOf'); - this._propColMaps.GetApproved = this._getPropertyColumnMapForEntity('GetApproved'); - this._propColMaps.IsApprovedForAll = this._getPropertyColumnMapForEntity('IsApprovedForAll'); - this._propColMaps.Name = this._getPropertyColumnMapForEntity('Name'); - this._propColMaps.Symbol = this._getPropertyColumnMapForEntity('Symbol'); - this._propColMaps.TokenURI = this._getPropertyColumnMapForEntity('TokenURI'); - this._propColMaps._Name = this._getPropertyColumnMapForEntity('_Name'); - this._propColMaps._Symbol = this._getPropertyColumnMapForEntity('_Symbol'); - this._propColMaps._Owners = this._getPropertyColumnMapForEntity('_Owners'); - this._propColMaps._Balances = this._getPropertyColumnMapForEntity('_Balances'); - this._propColMaps._TokenApprovals = this._getPropertyColumnMapForEntity('_TokenApprovals'); - this._propColMaps._OperatorApprovals = this._getPropertyColumnMapForEntity('_OperatorApprovals'); - } -} diff --git a/packages/erc721-watcher/src/entity/BalanceOf.ts b/packages/erc721-watcher/src/entity/BalanceOf.ts deleted file mode 100644 index bcc051d8..00000000 --- a/packages/erc721-watcher/src/entity/BalanceOf.ts +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'owner'], { unique: true }) -export class BalanceOf { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar', { length: 42 }) - owner!: string; - - @Column('numeric', { transformer: bigintTransformer }) - value!: bigint; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/erc721-watcher/src/entity/BlockProgress.ts b/packages/erc721-watcher/src/entity/BlockProgress.ts deleted file mode 100644 index e744aae4..00000000 --- a/packages/erc721-watcher/src/entity/BlockProgress.ts +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, CreateDateColumn } from 'typeorm'; -import { BlockProgressInterface } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash'], { unique: true }) -@Index(['blockNumber']) -@Index(['parentHash']) -export class BlockProgress implements BlockProgressInterface { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar') - cid!: string; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('varchar', { length: 66 }) - parentHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('integer') - blockTimestamp!: number; - - @Column('integer') - numEvents!: number; - - @Column('integer') - numProcessedEvents!: number; - - @Column('integer') - lastProcessedEventIndex!: number; - - @Column('boolean') - isComplete!: boolean; - - @Column('boolean', { default: false }) - isPruned!: boolean; - - @CreateDateColumn() - createdAt!: Date; -} diff --git a/packages/erc721-watcher/src/entity/Contract.ts b/packages/erc721-watcher/src/entity/Contract.ts deleted file mode 100644 index de66b387..00000000 --- a/packages/erc721-watcher/src/entity/Contract.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['address'], { unique: true }) -export class Contract { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 42 }) - address!: string; - - @Column('varchar') - kind!: string; - - @Column('boolean') - checkpoint!: boolean; - - @Column('integer') - startingBlock!: number; -} diff --git a/packages/erc721-watcher/src/entity/Event.ts b/packages/erc721-watcher/src/entity/Event.ts deleted file mode 100644 index 91f1e6d3..00000000 --- a/packages/erc721-watcher/src/entity/Event.ts +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, ManyToOne } from 'typeorm'; -import { BlockProgress } from './BlockProgress'; - -@Entity() -@Index(['block', 'contract']) -@Index(['block', 'contract', 'eventName']) -export class Event { - @PrimaryGeneratedColumn() - id!: number; - - @ManyToOne(() => BlockProgress, { onDelete: 'CASCADE' }) - block!: BlockProgress; - - @Column('varchar', { length: 66 }) - txHash!: string; - - @Column('integer') - index!: number; - - @Column('varchar', { length: 42 }) - contract!: string; - - @Column('varchar', { length: 256 }) - eventName!: string; - - @Column('text') - eventInfo!: string; - - @Column('text') - extraInfo!: string; - - @Column('text') - proof!: string; -} diff --git a/packages/erc721-watcher/src/entity/GetApproved.ts b/packages/erc721-watcher/src/entity/GetApproved.ts deleted file mode 100644 index 8f637e43..00000000 --- a/packages/erc721-watcher/src/entity/GetApproved.ts +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'tokenId'], { unique: true }) -export class GetApproved { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('numeric', { transformer: bigintTransformer }) - tokenId!: bigint; - - @Column('varchar') - value!: string; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/erc721-watcher/src/entity/IsApprovedForAll.ts b/packages/erc721-watcher/src/entity/IsApprovedForAll.ts deleted file mode 100644 index cd27dd7a..00000000 --- a/packages/erc721-watcher/src/entity/IsApprovedForAll.ts +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'owner', 'operator'], { unique: true }) -export class IsApprovedForAll { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar', { length: 42 }) - owner!: string; - - @Column('varchar', { length: 42 }) - operator!: string; - - @Column('boolean') - value!: boolean; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/erc721-watcher/src/entity/Name.ts b/packages/erc721-watcher/src/entity/Name.ts deleted file mode 100644 index c24431cc..00000000 --- a/packages/erc721-watcher/src/entity/Name.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockHash', 'contractAddress'], { unique: true }) -export class Name { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - value!: string; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/erc721-watcher/src/entity/OwnerOf.ts b/packages/erc721-watcher/src/entity/OwnerOf.ts deleted file mode 100644 index fb9a9edf..00000000 --- a/packages/erc721-watcher/src/entity/OwnerOf.ts +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'tokenId'], { unique: true }) -export class OwnerOf { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('numeric', { transformer: bigintTransformer }) - tokenId!: bigint; - - @Column('varchar') - value!: string; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/erc721-watcher/src/entity/State.ts b/packages/erc721-watcher/src/entity/State.ts deleted file mode 100644 index 10ef261e..00000000 --- a/packages/erc721-watcher/src/entity/State.ts +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, ManyToOne } from 'typeorm'; - -import { StateKind } from '@cerc-io/util'; - -import { BlockProgress } from './BlockProgress'; - -@Entity() -@Index(['cid'], { unique: true }) -@Index(['block', 'contractAddress']) -@Index(['block', 'contractAddress', 'kind'], { unique: true }) -export class State { - @PrimaryGeneratedColumn() - id!: number; - - @ManyToOne(() => BlockProgress, { onDelete: 'CASCADE' }) - block!: BlockProgress; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - cid!: string; - - @Column({ - type: 'enum', - enum: StateKind - }) - kind!: StateKind; - - @Column('bytea') - data!: Buffer; -} diff --git a/packages/erc721-watcher/src/entity/StateSyncStatus.ts b/packages/erc721-watcher/src/entity/StateSyncStatus.ts deleted file mode 100644 index c795212f..00000000 --- a/packages/erc721-watcher/src/entity/StateSyncStatus.ts +++ /dev/null @@ -1,17 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; - -@Entity() -export class StateSyncStatus { - @PrimaryGeneratedColumn() - id!: number; - - @Column('integer') - latestIndexedBlockNumber!: number; - - @Column('integer', { nullable: true }) - latestCheckpointBlockNumber!: number; -} diff --git a/packages/erc721-watcher/src/entity/SupportsInterface.ts b/packages/erc721-watcher/src/entity/SupportsInterface.ts deleted file mode 100644 index 3a8ed026..00000000 --- a/packages/erc721-watcher/src/entity/SupportsInterface.ts +++ /dev/null @@ -1,30 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'interfaceId'], { unique: true }) -export class SupportsInterface { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - interfaceId!: string; - - @Column('boolean') - value!: boolean; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/erc721-watcher/src/entity/Symbol.ts b/packages/erc721-watcher/src/entity/Symbol.ts deleted file mode 100644 index e80126af..00000000 --- a/packages/erc721-watcher/src/entity/Symbol.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockHash', 'contractAddress'], { unique: true }) -export class Symbol { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - value!: string; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/erc721-watcher/src/entity/SyncStatus.ts b/packages/erc721-watcher/src/entity/SyncStatus.ts deleted file mode 100644 index 19d0dfa7..00000000 --- a/packages/erc721-watcher/src/entity/SyncStatus.ts +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; -import { SyncStatusInterface } from '@cerc-io/util'; - -@Entity() -export class SyncStatus implements SyncStatusInterface { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - chainHeadBlockHash!: string; - - @Column('integer') - chainHeadBlockNumber!: number; - - @Column('varchar', { length: 66 }) - latestIndexedBlockHash!: string; - - @Column('integer') - latestIndexedBlockNumber!: number; - - @Column('varchar', { length: 66 }) - latestCanonicalBlockHash!: string; - - @Column('integer') - latestCanonicalBlockNumber!: number; - - @Column('varchar', { length: 66 }) - initialIndexedBlockHash!: string; - - @Column('integer') - initialIndexedBlockNumber!: number; -} diff --git a/packages/erc721-watcher/src/entity/TokenURI.ts b/packages/erc721-watcher/src/entity/TokenURI.ts deleted file mode 100644 index 512c2806..00000000 --- a/packages/erc721-watcher/src/entity/TokenURI.ts +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'tokenId'], { unique: true }) -export class TokenURI { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('numeric', { transformer: bigintTransformer }) - tokenId!: bigint; - - @Column('varchar') - value!: string; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/erc721-watcher/src/entity/TransferCount.ts b/packages/erc721-watcher/src/entity/TransferCount.ts deleted file mode 100644 index c586de13..00000000 --- a/packages/erc721-watcher/src/entity/TransferCount.ts +++ /dev/null @@ -1,23 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column } from 'typeorm'; - -@Entity() -export class TransferCount { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('integer') - count!: number; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/erc721-watcher/src/entity/_Balances.ts b/packages/erc721-watcher/src/entity/_Balances.ts deleted file mode 100644 index 559c77a3..00000000 --- a/packages/erc721-watcher/src/entity/_Balances.ts +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'key0'], { unique: true }) -export class _Balances { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar', { length: 42 }) - key0!: string; - - @Column('numeric', { transformer: bigintTransformer }) - value!: bigint; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/erc721-watcher/src/entity/_Name.ts b/packages/erc721-watcher/src/entity/_Name.ts deleted file mode 100644 index 5c6ba24a..00000000 --- a/packages/erc721-watcher/src/entity/_Name.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockHash', 'contractAddress'], { unique: true }) -export class _Name { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - value!: string; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/erc721-watcher/src/entity/_OperatorApprovals.ts b/packages/erc721-watcher/src/entity/_OperatorApprovals.ts deleted file mode 100644 index 732dd0d2..00000000 --- a/packages/erc721-watcher/src/entity/_OperatorApprovals.ts +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'key0', 'key1'], { unique: true }) -export class _OperatorApprovals { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar', { length: 42 }) - key0!: string; - - @Column('varchar', { length: 42 }) - key1!: string; - - @Column('boolean') - value!: boolean; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/erc721-watcher/src/entity/_Owners.ts b/packages/erc721-watcher/src/entity/_Owners.ts deleted file mode 100644 index caaee137..00000000 --- a/packages/erc721-watcher/src/entity/_Owners.ts +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'key0'], { unique: true }) -export class _Owners { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('numeric', { transformer: bigintTransformer }) - key0!: bigint; - - @Column('varchar') - value!: string; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/erc721-watcher/src/entity/_Symbol.ts b/packages/erc721-watcher/src/entity/_Symbol.ts deleted file mode 100644 index b3643d83..00000000 --- a/packages/erc721-watcher/src/entity/_Symbol.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockHash', 'contractAddress'], { unique: true }) -export class _Symbol { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - value!: string; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/erc721-watcher/src/entity/_TokenApprovals.ts b/packages/erc721-watcher/src/entity/_TokenApprovals.ts deleted file mode 100644 index c313565d..00000000 --- a/packages/erc721-watcher/src/entity/_TokenApprovals.ts +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'key0'], { unique: true }) -export class _TokenApprovals { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('numeric', { transformer: bigintTransformer }) - key0!: bigint; - - @Column('varchar') - value!: string; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/erc721-watcher/src/fill.ts b/packages/erc721-watcher/src/fill.ts deleted file mode 100644 index ba71cb0b..00000000 --- a/packages/erc721-watcher/src/fill.ts +++ /dev/null @@ -1,32 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { FillCmd } from '@cerc-io/cli'; - -import { Database } from './database'; -import { Indexer } from './indexer'; - -const log = debug('vulcanize:fill'); - -export const main = async (): Promise => { - const fillCmd = new FillCmd(); - await fillCmd.init(Database); - - await fillCmd.initIndexer(Indexer); - await fillCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(); -}); - -process.on('SIGINT', () => { - log(`Exiting process ${process.pid} with code 0`); - process.exit(0); -}); diff --git a/packages/erc721-watcher/src/gql/index.ts b/packages/erc721-watcher/src/gql/index.ts deleted file mode 100644 index 4732f682..00000000 --- a/packages/erc721-watcher/src/gql/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * as mutations from './mutations'; -export * as queries from './queries'; -export * as subscriptions from './subscriptions'; diff --git a/packages/erc721-watcher/src/gql/mutations/index.ts b/packages/erc721-watcher/src/gql/mutations/index.ts deleted file mode 100644 index 0c3bd853..00000000 --- a/packages/erc721-watcher/src/gql/mutations/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -import fs from 'fs'; -import path from 'path'; - -export const watchContract = fs.readFileSync(path.join(__dirname, 'watchContract.gql'), 'utf8'); diff --git a/packages/erc721-watcher/src/gql/mutations/watchContract.gql b/packages/erc721-watcher/src/gql/mutations/watchContract.gql deleted file mode 100644 index 2ecc74f7..00000000 --- a/packages/erc721-watcher/src/gql/mutations/watchContract.gql +++ /dev/null @@ -1,3 +0,0 @@ -mutation watchContract($address: String!, $kind: String!, $checkpoint: Boolean!, $startingBlock: Int){ - watchContract(address: $address, kind: $kind, checkpoint: $checkpoint, startingBlock: $startingBlock) -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/_balances.gql b/packages/erc721-watcher/src/gql/queries/_balances.gql deleted file mode 100644 index 2dd7805e..00000000 --- a/packages/erc721-watcher/src/gql/queries/_balances.gql +++ /dev/null @@ -1,8 +0,0 @@ -query _balances($blockHash: String!, $contractAddress: String!, $key0: String!){ - _balances(blockHash: $blockHash, contractAddress: $contractAddress, key0: $key0){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/_name.gql b/packages/erc721-watcher/src/gql/queries/_name.gql deleted file mode 100644 index 58ba0554..00000000 --- a/packages/erc721-watcher/src/gql/queries/_name.gql +++ /dev/null @@ -1,8 +0,0 @@ -query _name($blockHash: String!, $contractAddress: String!){ - _name(blockHash: $blockHash, contractAddress: $contractAddress){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/_operatorApprovals.gql b/packages/erc721-watcher/src/gql/queries/_operatorApprovals.gql deleted file mode 100644 index 3d89b84a..00000000 --- a/packages/erc721-watcher/src/gql/queries/_operatorApprovals.gql +++ /dev/null @@ -1,8 +0,0 @@ -query _operatorApprovals($blockHash: String!, $contractAddress: String!, $key0: String!, $key1: String!){ - _operatorApprovals(blockHash: $blockHash, contractAddress: $contractAddress, key0: $key0, key1: $key1){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/_owners.gql b/packages/erc721-watcher/src/gql/queries/_owners.gql deleted file mode 100644 index 8022b8b0..00000000 --- a/packages/erc721-watcher/src/gql/queries/_owners.gql +++ /dev/null @@ -1,8 +0,0 @@ -query _owners($blockHash: String!, $contractAddress: String!, $key0: BigInt!){ - _owners(blockHash: $blockHash, contractAddress: $contractAddress, key0: $key0){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/_symbol.gql b/packages/erc721-watcher/src/gql/queries/_symbol.gql deleted file mode 100644 index a5794794..00000000 --- a/packages/erc721-watcher/src/gql/queries/_symbol.gql +++ /dev/null @@ -1,8 +0,0 @@ -query _symbol($blockHash: String!, $contractAddress: String!){ - _symbol(blockHash: $blockHash, contractAddress: $contractAddress){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/_tokenApprovals.gql b/packages/erc721-watcher/src/gql/queries/_tokenApprovals.gql deleted file mode 100644 index 15199a97..00000000 --- a/packages/erc721-watcher/src/gql/queries/_tokenApprovals.gql +++ /dev/null @@ -1,8 +0,0 @@ -query _tokenApprovals($blockHash: String!, $contractAddress: String!, $key0: BigInt!){ - _tokenApprovals(blockHash: $blockHash, contractAddress: $contractAddress, key0: $key0){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/balanceOf.gql b/packages/erc721-watcher/src/gql/queries/balanceOf.gql deleted file mode 100644 index 40af44c4..00000000 --- a/packages/erc721-watcher/src/gql/queries/balanceOf.gql +++ /dev/null @@ -1,8 +0,0 @@ -query balanceOf($blockHash: String!, $contractAddress: String!, $owner: String!){ - balanceOf(blockHash: $blockHash, contractAddress: $contractAddress, owner: $owner){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/events.gql b/packages/erc721-watcher/src/gql/queries/events.gql deleted file mode 100644 index cd71e6ff..00000000 --- a/packages/erc721-watcher/src/gql/queries/events.gql +++ /dev/null @@ -1,39 +0,0 @@ -query events($blockHash: String!, $contractAddress: String!, $name: String){ - events(blockHash: $blockHash, contractAddress: $contractAddress, name: $name){ - block{ - cid - hash - number - timestamp - parentHash - } - tx{ - hash - index - from - to - } - contract - eventIndex - event{ - ... on ApprovalEvent { - owner - approved - tokenId - } - ... on ApprovalForAllEvent { - owner - operator - approved - } - ... on TransferEvent { - from - to - tokenId - } - } - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/eventsInRange.gql b/packages/erc721-watcher/src/gql/queries/eventsInRange.gql deleted file mode 100644 index 2cec4398..00000000 --- a/packages/erc721-watcher/src/gql/queries/eventsInRange.gql +++ /dev/null @@ -1,39 +0,0 @@ -query eventsInRange($fromBlockNumber: Int!, $toBlockNumber: Int!){ - eventsInRange(fromBlockNumber: $fromBlockNumber, toBlockNumber: $toBlockNumber){ - block{ - cid - hash - number - timestamp - parentHash - } - tx{ - hash - index - from - to - } - contract - eventIndex - event{ - ... on ApprovalEvent { - owner - approved - tokenId - } - ... on ApprovalForAllEvent { - owner - operator - approved - } - ... on TransferEvent { - from - to - tokenId - } - } - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/getApproved.gql b/packages/erc721-watcher/src/gql/queries/getApproved.gql deleted file mode 100644 index c290206d..00000000 --- a/packages/erc721-watcher/src/gql/queries/getApproved.gql +++ /dev/null @@ -1,8 +0,0 @@ -query getApproved($blockHash: String!, $contractAddress: String!, $tokenId: BigInt!){ - getApproved(blockHash: $blockHash, contractAddress: $contractAddress, tokenId: $tokenId){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/getState.gql b/packages/erc721-watcher/src/gql/queries/getState.gql deleted file mode 100644 index 3b8f6050..00000000 --- a/packages/erc721-watcher/src/gql/queries/getState.gql +++ /dev/null @@ -1,15 +0,0 @@ -query getState($blockHash: String!, $contractAddress: String!, $kind: String){ - getState(blockHash: $blockHash, contractAddress: $contractAddress, kind: $kind){ - block{ - cid - hash - number - timestamp - parentHash - } - contractAddress - cid - kind - data - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/getStateByCID.gql b/packages/erc721-watcher/src/gql/queries/getStateByCID.gql deleted file mode 100644 index 6c3c4fd8..00000000 --- a/packages/erc721-watcher/src/gql/queries/getStateByCID.gql +++ /dev/null @@ -1,15 +0,0 @@ -query getStateByCID($cid: String!){ - getStateByCID(cid: $cid){ - block{ - cid - hash - number - timestamp - parentHash - } - contractAddress - cid - kind - data - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/index.ts b/packages/erc721-watcher/src/gql/queries/index.ts deleted file mode 100644 index 7f33700c..00000000 --- a/packages/erc721-watcher/src/gql/queries/index.ts +++ /dev/null @@ -1,21 +0,0 @@ -import fs from 'fs'; -import path from 'path'; - -export const events = fs.readFileSync(path.join(__dirname, 'events.gql'), 'utf8'); -export const eventsInRange = fs.readFileSync(path.join(__dirname, 'eventsInRange.gql'), 'utf8'); -export const supportsInterface = fs.readFileSync(path.join(__dirname, 'supportsInterface.gql'), 'utf8'); -export const balanceOf = fs.readFileSync(path.join(__dirname, 'balanceOf.gql'), 'utf8'); -export const ownerOf = fs.readFileSync(path.join(__dirname, 'ownerOf.gql'), 'utf8'); -export const getApproved = fs.readFileSync(path.join(__dirname, 'getApproved.gql'), 'utf8'); -export const isApprovedForAll = fs.readFileSync(path.join(__dirname, 'isApprovedForAll.gql'), 'utf8'); -export const name = fs.readFileSync(path.join(__dirname, 'name.gql'), 'utf8'); -export const symbol = fs.readFileSync(path.join(__dirname, 'symbol.gql'), 'utf8'); -export const tokenURI = fs.readFileSync(path.join(__dirname, 'tokenURI.gql'), 'utf8'); -export const _name = fs.readFileSync(path.join(__dirname, '_name.gql'), 'utf8'); -export const _symbol = fs.readFileSync(path.join(__dirname, '_symbol.gql'), 'utf8'); -export const _owners = fs.readFileSync(path.join(__dirname, '_owners.gql'), 'utf8'); -export const _balances = fs.readFileSync(path.join(__dirname, '_balances.gql'), 'utf8'); -export const _tokenApprovals = fs.readFileSync(path.join(__dirname, '_tokenApprovals.gql'), 'utf8'); -export const _operatorApprovals = fs.readFileSync(path.join(__dirname, '_operatorApprovals.gql'), 'utf8'); -export const getStateByCID = fs.readFileSync(path.join(__dirname, 'getStateByCID.gql'), 'utf8'); -export const getState = fs.readFileSync(path.join(__dirname, 'getState.gql'), 'utf8'); diff --git a/packages/erc721-watcher/src/gql/queries/isApprovedForAll.gql b/packages/erc721-watcher/src/gql/queries/isApprovedForAll.gql deleted file mode 100644 index 6ea8ee5f..00000000 --- a/packages/erc721-watcher/src/gql/queries/isApprovedForAll.gql +++ /dev/null @@ -1,8 +0,0 @@ -query isApprovedForAll($blockHash: String!, $contractAddress: String!, $owner: String!, $operator: String!){ - isApprovedForAll(blockHash: $blockHash, contractAddress: $contractAddress, owner: $owner, operator: $operator){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/name.gql b/packages/erc721-watcher/src/gql/queries/name.gql deleted file mode 100644 index 0431f0d6..00000000 --- a/packages/erc721-watcher/src/gql/queries/name.gql +++ /dev/null @@ -1,8 +0,0 @@ -query name($blockHash: String!, $contractAddress: String!){ - name(blockHash: $blockHash, contractAddress: $contractAddress){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/ownerOf.gql b/packages/erc721-watcher/src/gql/queries/ownerOf.gql deleted file mode 100644 index 0c281503..00000000 --- a/packages/erc721-watcher/src/gql/queries/ownerOf.gql +++ /dev/null @@ -1,8 +0,0 @@ -query ownerOf($blockHash: String!, $contractAddress: String!, $tokenId: BigInt!){ - ownerOf(blockHash: $blockHash, contractAddress: $contractAddress, tokenId: $tokenId){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/supportsInterface.gql b/packages/erc721-watcher/src/gql/queries/supportsInterface.gql deleted file mode 100644 index 7cc2a2cd..00000000 --- a/packages/erc721-watcher/src/gql/queries/supportsInterface.gql +++ /dev/null @@ -1,8 +0,0 @@ -query supportsInterface($blockHash: String!, $contractAddress: String!, $interfaceId: String!){ - supportsInterface(blockHash: $blockHash, contractAddress: $contractAddress, interfaceId: $interfaceId){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/symbol.gql b/packages/erc721-watcher/src/gql/queries/symbol.gql deleted file mode 100644 index fa278b80..00000000 --- a/packages/erc721-watcher/src/gql/queries/symbol.gql +++ /dev/null @@ -1,8 +0,0 @@ -query symbol($blockHash: String!, $contractAddress: String!){ - symbol(blockHash: $blockHash, contractAddress: $contractAddress){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/queries/tokenURI.gql b/packages/erc721-watcher/src/gql/queries/tokenURI.gql deleted file mode 100644 index 80679694..00000000 --- a/packages/erc721-watcher/src/gql/queries/tokenURI.gql +++ /dev/null @@ -1,8 +0,0 @@ -query tokenURI($blockHash: String!, $contractAddress: String!, $tokenId: BigInt!){ - tokenURI(blockHash: $blockHash, contractAddress: $contractAddress, tokenId: $tokenId){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/gql/subscriptions/index.ts b/packages/erc721-watcher/src/gql/subscriptions/index.ts deleted file mode 100644 index f12910c5..00000000 --- a/packages/erc721-watcher/src/gql/subscriptions/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -import fs from 'fs'; -import path from 'path'; - -export const onEvent = fs.readFileSync(path.join(__dirname, 'onEvent.gql'), 'utf8'); diff --git a/packages/erc721-watcher/src/gql/subscriptions/onEvent.gql b/packages/erc721-watcher/src/gql/subscriptions/onEvent.gql deleted file mode 100644 index 25cf0c8a..00000000 --- a/packages/erc721-watcher/src/gql/subscriptions/onEvent.gql +++ /dev/null @@ -1,39 +0,0 @@ -subscription onEvent{ - onEvent{ - block{ - cid - hash - number - timestamp - parentHash - } - tx{ - hash - index - from - to - } - contract - eventIndex - event{ - ... on ApprovalEvent { - owner - approved - tokenId - } - ... on ApprovalForAllEvent { - owner - operator - approved - } - ... on TransferEvent { - from - to - tokenId - } - } - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/erc721-watcher/src/hooks.ts b/packages/erc721-watcher/src/hooks.ts deleted file mode 100644 index 322a6ab6..00000000 --- a/packages/erc721-watcher/src/hooks.ts +++ /dev/null @@ -1,145 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; - -import { updateStateForElementaryType, ResultEvent } from '@cerc-io/util'; - -import { Indexer } from './indexer'; -import { TransferCount } from './entity/TransferCount'; - -/** - * Hook function to store an initial state. - * @param indexer Indexer instance. - * @param blockHash Hash of the concerned block. - * @param contractAddress Address of the concerned contract. - * @returns Data block to be stored. - */ -export async function createInitialState (indexer: Indexer, contractAddress: string, blockHash: string): Promise { - assert(indexer); - assert(blockHash); - assert(contractAddress); - - // Store an empty State. - const stateData: any = { - state: {} - }; - - // Use updateStateForElementaryType to update initial state with an elementary property. - // Eg. const stateData = updateStateForElementaryType(stateData, '_totalBalance', result.value.toString()); - - // Use updateStateForMappingType to update initial state with a nested property. - // Eg. const stateData = updateStateForMappingType(stateData, '_allowances', [owner, spender], allowance.value.toString()); - - // Return initial state data to be saved. - return stateData; -} - -/** - * Hook function to create state diff. - * @param indexer Indexer instance that contains methods to fetch the contract variable values. - * @param blockHash Block hash of the concerned block. - */ -export async function createStateDiff (indexer: Indexer, blockHash: string): Promise { - assert(indexer); - assert(blockHash); - - // Use indexer.createDiff() method to save custom state diff(s). -} - -/** - * Hook function to create state checkpoint - * @param indexer Indexer instance. - * @param contractAddress Address of the concerned contract. - * @param blockHash Block hash of the concerned block. - * @returns Whether to disable default checkpoint. If false, the state from this hook is updated with that from default checkpoint. - */ -export async function createStateCheckpoint (indexer: Indexer, contractAddress: string, blockHash: string): Promise { - assert(indexer); - assert(blockHash); - assert(contractAddress); - - // Use indexer.createStateCheckpoint() method to create a custom checkpoint. - - // Return false to update the state created by this hook by auto-generated checkpoint state. - // Return true to disable update of the state created by this hook by auto-generated checkpoint state. - return false; -} - -/** - * Event hook function. - * @param indexer Indexer instance that contains methods to fetch and update the contract values in the database. - * @param eventData ResultEvent object containing event information. - */ -export async function handleEvent (indexer: Indexer, eventData: ResultEvent): Promise { - assert(indexer); - assert(eventData); - - // Perform indexing based on the type of event. - switch (eventData.event.__typename) { - case 'TransferEvent': { - // Get event fields from eventData. - const { from, to, tokenId } = eventData.event; - - // Update balance entry for the sender in database. - if (from !== '0x0000000000000000000000000000000000000000') { - await indexer._balances(eventData.block.hash, eventData.contract, from, true); - } - - // Update balance entry for the receiver in database. - if (to !== '0x0000000000000000000000000000000000000000') { - await indexer._balances(eventData.block.hash, eventData.contract, to, true); - } - - // Update owner for the tokenId in database. - await indexer._owners(eventData.block.hash, eventData.contract, tokenId, true); - - // Code to update a custom state property transferCount. - // { - // "transferCount": "1" - // } - // Fetch transferCount entity from database. - let transferCount = await indexer.getTransferCount(eventData.contract, eventData.block); - - if (!transferCount) { - transferCount = new TransferCount(); - transferCount.id = eventData.contract; - transferCount.count = 0; - } - - transferCount.blockHash = eventData.block.hash; - transferCount.blockNumber = eventData.block.number; - - // Increment count on transfer event. - transferCount.count++; - - // Update state for custom property transferCount. - const stateUpdate = updateStateForElementaryType({}, 'transferCount', transferCount.count); - await indexer.createDiffStaged(eventData.contract, eventData.block.hash, stateUpdate); - - // Save transferCount to database. - await indexer.saveOrUpdateTransferCount(transferCount); - - break; - } - case 'ApprovalEvent': { - // Get event fields from eventData. - const { tokenId } = eventData.event; - - // Update tokenApprovals for the tokenId in database. - await indexer._tokenApprovals(eventData.block.hash, eventData.contract, tokenId, true); - - break; - } - case 'ApprovalForAllEvent': { - // Get event fields from eventData. - const { owner, operator } = eventData.event; - - // Update operatorApprovals for the tokenId in database. - await indexer._operatorApprovals(eventData.block.hash, eventData.contract, owner, operator, true); - - break; - } - } -} diff --git a/packages/erc721-watcher/src/indexer.ts b/packages/erc721-watcher/src/indexer.ts deleted file mode 100644 index 4ad2ec22..00000000 --- a/packages/erc721-watcher/src/indexer.ts +++ /dev/null @@ -1,953 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import debug from 'debug'; -import { DeepPartial, FindConditions, FindManyOptions, In } from 'typeorm'; -import JSONbig from 'json-bigint'; -import { ethers } from 'ethers'; - -import { JsonFragment } from '@ethersproject/abi'; -import { BaseProvider } from '@ethersproject/providers'; -import { EthClient } from '@cerc-io/ipld-eth-client'; -import { MappingKey, StorageLayout } from '@cerc-io/solidity-mapper'; -import { - Indexer as BaseIndexer, - IndexerInterface, - ValueResult, - ServerConfig, - JobQueue, - Where, - QueryOptions, - updateStateForElementaryType, - updateStateForMappingType, - BlockHeight, - StateKind, - StateStatus, - ResultEvent, - getResultEvent, - DatabaseInterface, - Clients -} from '@cerc-io/util'; - -import ERC721Artifacts from './artifacts/ERC721.json'; -import { Database, ENTITIES } from './database'; -import { createInitialState, handleEvent, createStateDiff, createStateCheckpoint } from './hooks'; -import { Contract } from './entity/Contract'; -import { Event } from './entity/Event'; -import { SyncStatus } from './entity/SyncStatus'; -import { StateSyncStatus } from './entity/StateSyncStatus'; -import { BlockProgress } from './entity/BlockProgress'; -import { State } from './entity/State'; -import { TransferCount } from './entity/TransferCount'; - -const log = debug('vulcanize:indexer'); -const JSONbigNative = JSONbig({ useNativeBigInt: true }); - -const KIND_ERC721 = 'ERC721'; - -export class Indexer implements IndexerInterface { - _db: Database; - _ethClient: EthClient; - _ethProvider: BaseProvider; - _baseIndexer: BaseIndexer; - _serverConfig: ServerConfig; - - _abiMap: Map; - _storageLayoutMap: Map; - _contractMap: Map; - - constructor (serverConfig: ServerConfig, db: DatabaseInterface, clients: Clients, ethProvider: BaseProvider, jobQueue: JobQueue) { - assert(db); - assert(clients.ethClient); - - this._db = db as Database; - this._ethClient = clients.ethClient; - this._ethProvider = ethProvider; - this._serverConfig = serverConfig; - this._baseIndexer = new BaseIndexer(this._serverConfig, this._db, this._ethClient, this._ethProvider, jobQueue); - - this._abiMap = new Map(); - this._storageLayoutMap = new Map(); - this._contractMap = new Map(); - - const { - abi: ERC721ABI, - storageLayout: ERC721StorageLayout - } = ERC721Artifacts; - - assert(ERC721ABI); - this._abiMap.set(KIND_ERC721, ERC721ABI); - assert(ERC721StorageLayout); - this._storageLayoutMap.set(KIND_ERC721, ERC721StorageLayout); - this._contractMap.set(KIND_ERC721, new ethers.utils.Interface(ERC721ABI)); - } - - get serverConfig (): ServerConfig { - return this._serverConfig; - } - - get storageLayoutMap (): Map { - return this._storageLayoutMap; - } - - async init (): Promise { - await this._baseIndexer.fetchContracts(); - await this._baseIndexer.fetchStateStatus(); - } - - getResultEvent (event: Event): ResultEvent { - return getResultEvent(event); - } - - async supportsInterface (blockHash: string, contractAddress: string, interfaceId: string): Promise { - const entity = await this._db.getSupportsInterface({ blockHash, contractAddress, interfaceId }); - if (entity) { - log('supportsInterface: db hit.'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('supportsInterface: db miss, fetching from upstream server'); - - const { block: { number } } = await this._ethClient.getBlockByHash(blockHash); - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - const abi = this._abiMap.get(KIND_ERC721); - assert(abi); - - const contract = new ethers.Contract(contractAddress, abi, this._ethProvider); - const value = await contract.supportsInterface(interfaceId, { blockTag: blockHash }); - - const result: ValueResult = { value }; - - await this._db.saveSupportsInterface({ blockHash, blockNumber, contractAddress, interfaceId, value: result.value, proof: JSONbigNative.stringify(result.proof) }); - - return result; - } - - async balanceOf (blockHash: string, contractAddress: string, owner: string): Promise { - const entity = await this._db.getBalanceOf({ blockHash, contractAddress, owner }); - if (entity) { - log('balanceOf: db hit.'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('balanceOf: db miss, fetching from upstream server'); - - const { block: { number } } = await this._ethClient.getBlockByHash(blockHash); - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - const abi = this._abiMap.get(KIND_ERC721); - assert(abi); - - const contract = new ethers.Contract(contractAddress, abi, this._ethProvider); - let value = await contract.balanceOf(owner, { blockTag: blockHash }); - value = value.toString(); - value = BigInt(value); - - const result: ValueResult = { value }; - - await this._db.saveBalanceOf({ blockHash, blockNumber, contractAddress, owner, value: result.value, proof: JSONbigNative.stringify(result.proof) }); - - return result; - } - - async ownerOf (blockHash: string, contractAddress: string, tokenId: bigint): Promise { - const entity = await this._db.getOwnerOf({ blockHash, contractAddress, tokenId }); - if (entity) { - log('ownerOf: db hit.'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('ownerOf: db miss, fetching from upstream server'); - - const { block: { number } } = await this._ethClient.getBlockByHash(blockHash); - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - const abi = this._abiMap.get(KIND_ERC721); - assert(abi); - - const contract = new ethers.Contract(contractAddress, abi, this._ethProvider); - const value = await contract.ownerOf(tokenId, { blockTag: blockHash }); - - const result: ValueResult = { value }; - - await this._db.saveOwnerOf({ blockHash, blockNumber, contractAddress, tokenId, value: result.value, proof: JSONbigNative.stringify(result.proof) }); - - return result; - } - - async getApproved (blockHash: string, contractAddress: string, tokenId: bigint): Promise { - const entity = await this._db.getGetApproved({ blockHash, contractAddress, tokenId }); - if (entity) { - log('getApproved: db hit.'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('getApproved: db miss, fetching from upstream server'); - - const { block: { number } } = await this._ethClient.getBlockByHash(blockHash); - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - const abi = this._abiMap.get(KIND_ERC721); - assert(abi); - - const contract = new ethers.Contract(contractAddress, abi, this._ethProvider); - const value = await contract.getApproved(tokenId, { blockTag: blockHash }); - - const result: ValueResult = { value }; - - await this._db.saveGetApproved({ blockHash, blockNumber, contractAddress, tokenId, value: result.value, proof: JSONbigNative.stringify(result.proof) }); - - return result; - } - - async isApprovedForAll (blockHash: string, contractAddress: string, owner: string, operator: string): Promise { - const entity = await this._db.getIsApprovedForAll({ blockHash, contractAddress, owner, operator }); - if (entity) { - log('isApprovedForAll: db hit.'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('isApprovedForAll: db miss, fetching from upstream server'); - - const { block: { number } } = await this._ethClient.getBlockByHash(blockHash); - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - const abi = this._abiMap.get(KIND_ERC721); - assert(abi); - - const contract = new ethers.Contract(contractAddress, abi, this._ethProvider); - const value = await contract.isApprovedForAll(owner, operator, { blockTag: blockHash }); - - const result: ValueResult = { value }; - - await this._db.saveIsApprovedForAll({ blockHash, blockNumber, contractAddress, owner, operator, value: result.value, proof: JSONbigNative.stringify(result.proof) }); - - return result; - } - - async name (blockHash: string, contractAddress: string): Promise { - const entity = await this._db.getName({ blockHash, contractAddress }); - if (entity) { - log('name: db hit.'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('name: db miss, fetching from upstream server'); - - const { block: { number } } = await this._ethClient.getBlockByHash(blockHash); - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - const abi = this._abiMap.get(KIND_ERC721); - assert(abi); - - const contract = new ethers.Contract(contractAddress, abi, this._ethProvider); - const value = await contract.name({ blockTag: blockHash }); - - const result: ValueResult = { value }; - - await this._db.saveName({ blockHash, blockNumber, contractAddress, value: result.value, proof: JSONbigNative.stringify(result.proof) }); - - return result; - } - - async symbol (blockHash: string, contractAddress: string): Promise { - const entity = await this._db.getSymbol({ blockHash, contractAddress }); - if (entity) { - log('symbol: db hit.'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('symbol: db miss, fetching from upstream server'); - - const { block: { number } } = await this._ethClient.getBlockByHash(blockHash); - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - const abi = this._abiMap.get(KIND_ERC721); - assert(abi); - - const contract = new ethers.Contract(contractAddress, abi, this._ethProvider); - const value = await contract.symbol({ blockTag: blockHash }); - - const result: ValueResult = { value }; - - await this._db.saveSymbol({ blockHash, blockNumber, contractAddress, value: result.value, proof: JSONbigNative.stringify(result.proof) }); - - return result; - } - - async tokenURI (blockHash: string, contractAddress: string, tokenId: bigint): Promise { - const entity = await this._db.getTokenURI({ blockHash, contractAddress, tokenId }); - if (entity) { - log('tokenURI: db hit.'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('tokenURI: db miss, fetching from upstream server'); - - const { block: { number } } = await this._ethClient.getBlockByHash(blockHash); - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - const abi = this._abiMap.get(KIND_ERC721); - assert(abi); - - const contract = new ethers.Contract(contractAddress, abi, this._ethProvider); - const value = await contract.tokenURI(tokenId, { blockTag: blockHash }); - - const result: ValueResult = { value }; - - await this._db.saveTokenURI({ blockHash, blockNumber, contractAddress, tokenId, value: result.value, proof: JSONbigNative.stringify(result.proof) }); - - return result; - } - - async getTransferCount (id: string, block: BlockHeight): Promise { - const dbTx = await this._db.createTransactionRunner(); - let res; - - try { - res = await this._db.getTransferCount(dbTx, { id, blockHash: block.hash, blockNumber: block.number }); - await dbTx.commitTransaction(); - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - - return res; - } - - async saveOrUpdateTransferCount (transferCount: TransferCount): Promise { - const dbTx = await this._db.createTransactionRunner(); - - try { - await this._db.saveTransferCount(dbTx, transferCount); - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - } - - async _name (blockHash: string, contractAddress: string, diff = false): Promise { - const entity = await this._db._getName({ blockHash, contractAddress }); - if (entity) { - log('_name: db hit.'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('_name: db miss, fetching from upstream server'); - - const { block: { number } } = await this._ethClient.getBlockByHash(blockHash); - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - const storageLayout = this._storageLayoutMap.get(KIND_ERC721); - assert(storageLayout); - - const result = await this._baseIndexer.getStorageValue( - storageLayout, - blockHash, - contractAddress, - '_name' - ); - - await this._db._saveName({ blockHash, blockNumber, contractAddress, value: result.value, proof: JSONbigNative.stringify(result.proof) }); - - if (diff) { - const stateUpdate = updateStateForElementaryType({}, '_name', result.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - - return result; - } - - async _symbol (blockHash: string, contractAddress: string, diff = false): Promise { - const entity = await this._db._getSymbol({ blockHash, contractAddress }); - if (entity) { - log('_symbol: db hit.'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('_symbol: db miss, fetching from upstream server'); - - const { block: { number } } = await this._ethClient.getBlockByHash(blockHash); - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - const storageLayout = this._storageLayoutMap.get(KIND_ERC721); - assert(storageLayout); - - const result = await this._baseIndexer.getStorageValue( - storageLayout, - blockHash, - contractAddress, - '_symbol' - ); - - await this._db._saveSymbol({ blockHash, blockNumber, contractAddress, value: result.value, proof: JSONbigNative.stringify(result.proof) }); - - if (diff) { - const stateUpdate = updateStateForElementaryType({}, '_symbol', result.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - - return result; - } - - async _owners (blockHash: string, contractAddress: string, key0: bigint, diff = false): Promise { - const entity = await this._db._getOwners({ blockHash, contractAddress, key0 }); - if (entity) { - log('_owners: db hit.'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('_owners: db miss, fetching from upstream server'); - - const { block: { number } } = await this._ethClient.getBlockByHash(blockHash); - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - const storageLayout = this._storageLayoutMap.get(KIND_ERC721); - assert(storageLayout); - - const result = await this._baseIndexer.getStorageValue( - storageLayout, - blockHash, - contractAddress, - '_owners', - key0 - ); - - await this._db._saveOwners({ blockHash, blockNumber, contractAddress, key0, value: result.value, proof: JSONbigNative.stringify(result.proof) }); - - if (diff) { - const stateUpdate = updateStateForMappingType({}, '_owners', [key0.toString()], result.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - - return result; - } - - async _balances (blockHash: string, contractAddress: string, key0: string, diff = false): Promise { - const entity = await this._db._getBalances({ blockHash, contractAddress, key0 }); - if (entity) { - log('_balances: db hit.'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('_balances: db miss, fetching from upstream server'); - - const { block: { number } } = await this._ethClient.getBlockByHash(blockHash); - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - const storageLayout = this._storageLayoutMap.get(KIND_ERC721); - assert(storageLayout); - - const result = await this._baseIndexer.getStorageValue( - storageLayout, - blockHash, - contractAddress, - '_balances', - key0 - ); - - await this._db._saveBalances({ blockHash, blockNumber, contractAddress, key0, value: result.value, proof: JSONbigNative.stringify(result.proof) }); - - if (diff) { - const stateUpdate = updateStateForMappingType({}, '_balances', [key0.toString()], result.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - - return result; - } - - async _tokenApprovals (blockHash: string, contractAddress: string, key0: bigint, diff = false): Promise { - const entity = await this._db._getTokenApprovals({ blockHash, contractAddress, key0 }); - if (entity) { - log('_tokenApprovals: db hit.'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('_tokenApprovals: db miss, fetching from upstream server'); - - const { block: { number } } = await this._ethClient.getBlockByHash(blockHash); - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - const storageLayout = this._storageLayoutMap.get(KIND_ERC721); - assert(storageLayout); - - const result = await this._baseIndexer.getStorageValue( - storageLayout, - blockHash, - contractAddress, - '_tokenApprovals', - key0 - ); - - await this._db._saveTokenApprovals({ blockHash, blockNumber, contractAddress, key0, value: result.value, proof: JSONbigNative.stringify(result.proof) }); - - if (diff) { - const stateUpdate = updateStateForMappingType({}, '_tokenApprovals', [key0.toString()], result.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - - return result; - } - - async _operatorApprovals (blockHash: string, contractAddress: string, key0: string, key1: string, diff = false): Promise { - const entity = await this._db._getOperatorApprovals({ blockHash, contractAddress, key0, key1 }); - if (entity) { - log('_operatorApprovals: db hit.'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('_operatorApprovals: db miss, fetching from upstream server'); - - const { block: { number } } = await this._ethClient.getBlockByHash(blockHash); - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - const storageLayout = this._storageLayoutMap.get(KIND_ERC721); - assert(storageLayout); - - const result = await this._baseIndexer.getStorageValue( - storageLayout, - blockHash, - contractAddress, - '_operatorApprovals', - key0, - key1 - ); - - await this._db._saveOperatorApprovals({ blockHash, blockNumber, contractAddress, key0, key1, value: result.value, proof: JSONbigNative.stringify(result.proof) }); - - if (diff) { - const stateUpdate = updateStateForMappingType({}, '_operatorApprovals', [key0.toString(), key1.toString()], result.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - - return result; - } - - async getStorageValue (storageLayout: StorageLayout, blockHash: string, contractAddress: string, variable: string, ...mappingKeys: MappingKey[]): Promise { - return this._baseIndexer.getStorageValue( - storageLayout, - blockHash, - contractAddress, - variable, - ...mappingKeys - ); - } - - async getEntitiesForBlock (blockHash: string, tableName: string): Promise { - return this._db.getEntitiesForBlock(blockHash, tableName); - } - - async processInitialState (contractAddress: string, blockHash: string): Promise { - // Call initial state hook. - return createInitialState(this, contractAddress, blockHash); - } - - async processStateCheckpoint (contractAddress: string, blockHash: string): Promise { - // Call checkpoint hook. - return createStateCheckpoint(this, contractAddress, blockHash); - } - - async processCanonicalBlock (blockHash: string): Promise { - console.time('time:indexer#processCanonicalBlock-finalize_auto_diffs'); - // Finalize staged diff blocks if any. - await this._baseIndexer.finalizeDiffStaged(blockHash); - console.timeEnd('time:indexer#processCanonicalBlock-finalize_auto_diffs'); - - // Call custom stateDiff hook. - await createStateDiff(this, blockHash); - } - - async processCheckpoint (blockHash: string): Promise { - // Return if checkpointInterval is <= 0. - const checkpointInterval = this._serverConfig.checkpointInterval; - if (checkpointInterval <= 0) return; - - console.time('time:indexer#processCheckpoint-checkpoint'); - await this._baseIndexer.processCheckpoint(this, blockHash, checkpointInterval); - console.timeEnd('time:indexer#processCheckpoint-checkpoint'); - } - - async processCLICheckpoint (contractAddress: string, blockHash?: string): Promise { - return this._baseIndexer.processCLICheckpoint(this, contractAddress, blockHash); - } - - async getPrevState (blockHash: string, contractAddress: string, kind?: string): Promise { - return this._db.getPrevState(blockHash, contractAddress, kind); - } - - async getLatestState (contractAddress: string, kind: StateKind | null, blockNumber?: number): Promise { - return this._db.getLatestState(contractAddress, kind, blockNumber); - } - - async getStatesByHash (blockHash: string): Promise { - return this._baseIndexer.getStatesByHash(blockHash); - } - - async getStateByCID (cid: string): Promise { - return this._baseIndexer.getStateByCID(cid); - } - - async getStates (where: FindConditions): Promise { - return this._db.getStates(where); - } - - getStateData (state: State): any { - return this._baseIndexer.getStateData(state); - } - - // Method used to create auto diffs (diff_staged). - async createDiffStaged (contractAddress: string, blockHash: string, data: any): Promise { - console.time('time:indexer#createDiffStaged-auto_diff'); - await this._baseIndexer.createDiffStaged(contractAddress, blockHash, data); - console.timeEnd('time:indexer#createDiffStaged-auto_diff'); - } - - // Method to be used by createStateDiff hook. - async createDiff (contractAddress: string, blockHash: string, data: any): Promise { - const block = await this.getBlockProgress(blockHash); - assert(block); - - await this._baseIndexer.createDiff(contractAddress, block, data); - } - - // Method to be used by createStateCheckpoint hook. - async createStateCheckpoint (contractAddress: string, blockHash: string, data: any): Promise { - const block = await this.getBlockProgress(blockHash); - assert(block); - - return this._baseIndexer.createStateCheckpoint(contractAddress, block, data); - } - - // Method to be used by export-state CLI. - async createCheckpoint (contractAddress: string, blockHash: string): Promise { - const block = await this.getBlockProgress(blockHash); - assert(block); - - return this._baseIndexer.createCheckpoint(this, contractAddress, block); - } - - async saveOrUpdateState (state: State): Promise { - return this._baseIndexer.saveOrUpdateState(state); - } - - async removeStates (blockNumber: number, kind: StateKind): Promise { - await this._baseIndexer.removeStates(blockNumber, kind); - } - - async triggerIndexingOnEvent (event: Event): Promise { - const resultEvent = this.getResultEvent(event); - - // Call custom hook function for indexing on event. - await handleEvent(this, resultEvent); - } - - async processEvent (event: Event): Promise { - // Trigger indexing of data based on the event. - await this.triggerIndexingOnEvent(event); - } - - async processBlock (blockProgress: BlockProgress): Promise { - console.time('time:indexer#processBlock-init_state'); - // Call a function to create initial state for contracts. - await this._baseIndexer.createInit(this, blockProgress.blockHash, blockProgress.blockNumber); - console.timeEnd('time:indexer#processBlock-init_state'); - } - - parseEventNameAndArgs (kind: string, logObj: any): any { - const { topics, data } = logObj; - - const contract = this._contractMap.get(kind); - assert(contract); - - const logDescription = contract.parseLog({ data, topics }); - - const { eventName, eventInfo, eventSignature } = this._baseIndexer.parseEvent(logDescription); - - return { - eventName, - eventInfo, - eventSignature - }; - } - - async getStateSyncStatus (): Promise { - return this._db.getStateSyncStatus(); - } - - async updateStateSyncStatusIndexedBlock (blockNumber: number, force?: boolean): Promise { - const dbTx = await this._db.createTransactionRunner(); - let res; - - try { - res = await this._db.updateStateSyncStatusIndexedBlock(dbTx, blockNumber, force); - await dbTx.commitTransaction(); - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - - return res; - } - - async updateStateSyncStatusCheckpointBlock (blockNumber: number, force?: boolean): Promise { - const dbTx = await this._db.createTransactionRunner(); - let res; - - try { - res = await this._db.updateStateSyncStatusCheckpointBlock(dbTx, blockNumber, force); - await dbTx.commitTransaction(); - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - - return res; - } - - async getLatestCanonicalBlock (): Promise { - const syncStatus = await this.getSyncStatus(); - assert(syncStatus); - - const latestCanonicalBlock = await this.getBlockProgress(syncStatus.latestCanonicalBlockHash); - assert(latestCanonicalBlock); - - return latestCanonicalBlock; - } - - async getLatestStateIndexedBlock (): Promise { - return this._baseIndexer.getLatestStateIndexedBlock(); - } - - async watchContract (address: string, kind: string, checkpoint: boolean, startingBlock: number): Promise { - return this._baseIndexer.watchContract(address, kind, checkpoint, startingBlock); - } - - updateStateStatusMap (address: string, stateStatus: StateStatus): void { - this._baseIndexer.updateStateStatusMap(address, stateStatus); - } - - cacheContract (contract: Contract): void { - return this._baseIndexer.cacheContract(contract); - } - - async saveEventEntity (dbEvent: Event): Promise { - return this._baseIndexer.saveEventEntity(dbEvent); - } - - async getEventsByFilter (blockHash: string, contract?: string, name?: string): Promise> { - return this._baseIndexer.getEventsByFilter(blockHash, contract, name); - } - - isWatchedContract (address : string): Contract | undefined { - return this._baseIndexer.isWatchedContract(address); - } - - getContractsByKind (kind: string): Contract[] { - return this._baseIndexer.getContractsByKind(kind); - } - - async getProcessedBlockCountForRange (fromBlockNumber: number, toBlockNumber: number): Promise<{ expected: number, actual: number }> { - return this._baseIndexer.getProcessedBlockCountForRange(fromBlockNumber, toBlockNumber); - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise> { - return this._baseIndexer.getEventsInRange(fromBlockNumber, toBlockNumber); - } - - async getSyncStatus (): Promise { - return this._baseIndexer.getSyncStatus(); - } - - async getBlocks (blockFilter: { blockHash?: string, blockNumber?: number }): Promise { - return this._baseIndexer.getBlocks(blockFilter); - } - - async updateSyncStatusIndexedBlock (blockHash: string, blockNumber: number, force = false): Promise { - return this._baseIndexer.updateSyncStatusIndexedBlock(blockHash, blockNumber, force); - } - - async updateSyncStatusChainHead (blockHash: string, blockNumber: number, force = false): Promise { - return this._baseIndexer.updateSyncStatusChainHead(blockHash, blockNumber, force); - } - - async updateSyncStatusCanonicalBlock (blockHash: string, blockNumber: number, force = false): Promise { - return this._baseIndexer.updateSyncStatusCanonicalBlock(blockHash, blockNumber, force); - } - - async getEvent (id: string): Promise { - return this._baseIndexer.getEvent(id); - } - - async getBlockProgress (blockHash: string): Promise { - return this._baseIndexer.getBlockProgress(blockHash); - } - - async getBlockProgressEntities (where: FindConditions, options: FindManyOptions): Promise { - return this._baseIndexer.getBlockProgressEntities(where, options); - } - - async getBlocksAtHeight (height: number, isPruned: boolean): Promise { - return this._baseIndexer.getBlocksAtHeight(height, isPruned); - } - - async saveBlockAndFetchEvents (block: DeepPartial): Promise<[BlockProgress, DeepPartial[]]> { - return this._saveBlockAndFetchEvents(block); - } - - async getBlockEvents (blockHash: string, where: Where, queryOptions: QueryOptions): Promise> { - return this._baseIndexer.getBlockEvents(blockHash, where, queryOptions); - } - - async removeUnknownEvents (block: BlockProgress): Promise { - return this._baseIndexer.removeUnknownEvents(Event, block); - } - - async markBlocksAsPruned (blocks: BlockProgress[]): Promise { - await this._baseIndexer.markBlocksAsPruned(blocks); - - await this._pruneEntities(blocks); - } - - // Prune custom entities. - async _pruneEntities (blocks: BlockProgress[]): Promise { - const entityTypes = [TransferCount]; - const blockHashes = blocks.map(block => block.blockHash); - - const dbTx = await this._db.createTransactionRunner(); - - try { - const updatePromises = entityTypes.map(async entityType => { - await this._db.updateEntity( - dbTx, - entityType, - { blockHash: In(blockHashes) }, - { isPruned: true } - ); - }); - - await Promise.all(updatePromises); - await dbTx.commitTransaction(); - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - } - - async updateBlockProgress (block: BlockProgress, lastProcessedEventIndex: number): Promise { - return this._baseIndexer.updateBlockProgress(block, lastProcessedEventIndex); - } - - async getAncestorAtDepth (blockHash: string, depth: number): Promise { - return this._baseIndexer.getAncestorAtDepth(blockHash, depth); - } - - async resetWatcherToBlock (blockNumber: number): Promise { - const entities = [...ENTITIES]; - await this._baseIndexer.resetWatcherToBlock(blockNumber, entities); - } - - async _saveBlockAndFetchEvents ({ - cid: blockCid, - blockHash, - blockNumber, - blockTimestamp, - parentHash - }: DeepPartial): Promise<[BlockProgress, DeepPartial[]]> { - assert(blockHash); - assert(blockNumber); - - const dbEvents = await this._baseIndexer.fetchEvents(blockHash, blockNumber, this.parseEventNameAndArgs.bind(this)); - - const dbTx = await this._db.createTransactionRunner(); - try { - const block = { - cid: blockCid, - blockHash, - blockNumber, - blockTimestamp, - parentHash - }; - - console.time(`time:indexer#_saveBlockAndFetchEvents-db-save-${blockNumber}`); - const blockProgress = await this._db.saveBlockWithEvents(dbTx, block, dbEvents); - await dbTx.commitTransaction(); - console.timeEnd(`time:indexer#_saveBlockAndFetchEvents-db-save-${blockNumber}`); - - return [blockProgress, []]; - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - } -} diff --git a/packages/erc721-watcher/src/job-runner.ts b/packages/erc721-watcher/src/job-runner.ts deleted file mode 100644 index 92e57187..00000000 --- a/packages/erc721-watcher/src/job-runner.ts +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import debug from 'debug'; - -import { JobRunnerCmd } from '@cerc-io/cli'; -import { JobRunner } from '@cerc-io/util'; - -import { Indexer } from './indexer'; -import { Database } from './database'; - -const log = debug('vulcanize:job-runner'); - -export const main = async (): Promise => { - const jobRunnerCmd = new JobRunnerCmd(); - await jobRunnerCmd.init(Database); - await jobRunnerCmd.initIndexer(Indexer); - - await jobRunnerCmd.exec(async (jobRunner: JobRunner): Promise => { - await jobRunner.subscribeBlockProcessingQueue(); - await jobRunner.subscribeEventProcessingQueue(); - await jobRunner.subscribeBlockCheckpointQueue(); - await jobRunner.subscribeHooksQueue(); - }); -}; - -main().then(() => { - log('Starting job runner...'); -}).catch(err => { - log(err); -}); - -process.on('uncaughtException', err => { - log('uncaughtException', err); -}); diff --git a/packages/erc721-watcher/src/resolvers.ts b/packages/erc721-watcher/src/resolvers.ts deleted file mode 100644 index a1b7d4ad..00000000 --- a/packages/erc721-watcher/src/resolvers.ts +++ /dev/null @@ -1,183 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import BigInt from 'apollo-type-bigint'; -import debug from 'debug'; -import Decimal from 'decimal.js'; -import { GraphQLScalarType } from 'graphql'; - -import { ValueResult, BlockHeight, getResultState, IndexerInterface, EventWatcher } from '@cerc-io/util'; - -import { Indexer } from './indexer'; - -const log = debug('vulcanize:resolver'); - -export const createResolvers = async (indexerArg: IndexerInterface, eventWatcher: EventWatcher): Promise => { - const indexer = indexerArg as Indexer; - - return { - BigInt: new BigInt('bigInt'), - - BigDecimal: new GraphQLScalarType({ - name: 'BigDecimal', - description: 'BigDecimal custom scalar type', - parseValue (value) { - // value from the client - return new Decimal(value); - }, - serialize (value: Decimal) { - // value sent to the client - return value.toFixed(); - } - }), - - Event: { - __resolveType: (obj: any) => { - assert(obj.__typename); - - return obj.__typename; - } - }, - - Subscription: { - onEvent: { - subscribe: () => eventWatcher.getEventIterator() - } - }, - - Mutation: { - watchContract: async (_: any, { address, kind, checkpoint, startingBlock = 1 }: { address: string, kind: string, checkpoint: boolean, startingBlock: number }): Promise => { - log('watchContract', address, kind, checkpoint, startingBlock); - await indexer.watchContract(address, kind, checkpoint, startingBlock); - - return true; - } - }, - - Query: { - supportsInterface: (_: any, { blockHash, contractAddress, interfaceId }: { blockHash: string, contractAddress: string, interfaceId: string }): Promise => { - log('supportsInterface', blockHash, contractAddress, interfaceId); - return indexer.supportsInterface(blockHash, contractAddress, interfaceId); - }, - - balanceOf: (_: any, { blockHash, contractAddress, owner }: { blockHash: string, contractAddress: string, owner: string }): Promise => { - log('balanceOf', blockHash, contractAddress, owner); - return indexer.balanceOf(blockHash, contractAddress, owner); - }, - - ownerOf: (_: any, { blockHash, contractAddress, tokenId }: { blockHash: string, contractAddress: string, tokenId: bigint }): Promise => { - log('ownerOf', blockHash, contractAddress, tokenId); - return indexer.ownerOf(blockHash, contractAddress, tokenId); - }, - - getApproved: (_: any, { blockHash, contractAddress, tokenId }: { blockHash: string, contractAddress: string, tokenId: bigint }): Promise => { - log('getApproved', blockHash, contractAddress, tokenId); - return indexer.getApproved(blockHash, contractAddress, tokenId); - }, - - isApprovedForAll: (_: any, { blockHash, contractAddress, owner, operator }: { blockHash: string, contractAddress: string, owner: string, operator: string }): Promise => { - log('isApprovedForAll', blockHash, contractAddress, owner, operator); - return indexer.isApprovedForAll(blockHash, contractAddress, owner, operator); - }, - - name: (_: any, { blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise => { - log('name', blockHash, contractAddress); - return indexer.name(blockHash, contractAddress); - }, - - symbol: (_: any, { blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise => { - log('symbol', blockHash, contractAddress); - return indexer.symbol(blockHash, contractAddress); - }, - - tokenURI: (_: any, { blockHash, contractAddress, tokenId }: { blockHash: string, contractAddress: string, tokenId: bigint }): Promise => { - log('tokenURI', blockHash, contractAddress, tokenId); - return indexer.tokenURI(blockHash, contractAddress, tokenId); - }, - - _name: (_: any, { blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise => { - log('_name', blockHash, contractAddress); - return indexer._name(blockHash, contractAddress); - }, - - _symbol: (_: any, { blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise => { - log('_symbol', blockHash, contractAddress); - return indexer._symbol(blockHash, contractAddress); - }, - - _owners: (_: any, { blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: bigint }): Promise => { - log('_owners', blockHash, contractAddress, key0); - return indexer._owners(blockHash, contractAddress, key0); - }, - - _balances: (_: any, { blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: string }): Promise => { - log('_balances', blockHash, contractAddress, key0); - return indexer._balances(blockHash, contractAddress, key0); - }, - - _tokenApprovals: (_: any, { blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: bigint }): Promise => { - log('_tokenApprovals', blockHash, contractAddress, key0); - return indexer._tokenApprovals(blockHash, contractAddress, key0); - }, - - _operatorApprovals: (_: any, { blockHash, contractAddress, key0, key1 }: { blockHash: string, contractAddress: string, key0: string, key1: string }): Promise => { - log('_operatorApprovals', blockHash, contractAddress, key0, key1); - return indexer._operatorApprovals(blockHash, contractAddress, key0, key1); - }, - - transferCount: async (_: any, { id, block = {} }: { id: string, block: BlockHeight }) => { - log('transferCount', id, block); - - return indexer.getTransferCount(id, block); - }, - - events: async (_: any, { blockHash, contractAddress, name }: { blockHash: string, contractAddress: string, name?: string }) => { - log('events', blockHash, contractAddress, name); - - const block = await indexer.getBlockProgress(blockHash); - if (!block || !block.isComplete) { - throw new Error(`Block hash ${blockHash} number ${block?.blockNumber} not processed yet`); - } - - const events = await indexer.getEventsByFilter(blockHash, contractAddress, name); - return events.map(event => indexer.getResultEvent(event)); - }, - - eventsInRange: async (_: any, { fromBlockNumber, toBlockNumber }: { fromBlockNumber: number, toBlockNumber: number }) => { - log('eventsInRange', fromBlockNumber, toBlockNumber); - - const { expected, actual } = await indexer.getProcessedBlockCountForRange(fromBlockNumber, toBlockNumber); - if (expected !== actual) { - throw new Error(`Range not available, expected ${expected}, got ${actual} blocks in range`); - } - - const events = await indexer.getEventsInRange(fromBlockNumber, toBlockNumber); - return events.map(event => indexer.getResultEvent(event)); - }, - - getStateByCID: async (_: any, { cid }: { cid: string }) => { - log('getStateByCID', cid); - - const state = await indexer.getStateByCID(cid); - - return state && state.block.isComplete ? getResultState(state) : undefined; - }, - - getState: async (_: any, { blockHash, contractAddress, kind }: { blockHash: string, contractAddress: string, kind: string }) => { - log('getState', blockHash, contractAddress, kind); - - const state = await indexer.getPrevState(blockHash, contractAddress, kind); - - return state && state.block.isComplete ? getResultState(state) : undefined; - }, - - getSyncStatus: async () => { - log('getSyncStatus'); - - return indexer.getSyncStatus(); - } - } - }; -}; diff --git a/packages/erc721-watcher/src/schema.gql b/packages/erc721-watcher/src/schema.gql deleted file mode 100644 index 7b15b148..00000000 --- a/packages/erc721-watcher/src/schema.gql +++ /dev/null @@ -1,129 +0,0 @@ -scalar BigInt - -scalar BigDecimal - -scalar Bytes - -input Block_height { - hash: Bytes - number: Int -} - -type Proof { - data: String! -} - -type ResultBoolean { - value: Boolean! - proof: Proof -} - -type ResultString { - value: String! - proof: Proof -} - -type ResultInt { - value: Int! - proof: Proof -} - -type ResultBigInt { - value: BigInt! - proof: Proof -} - -type _Block_ { - cid: String! - hash: String! - number: Int! - timestamp: Int! - parentHash: String! -} - -type _Transaction_ { - hash: String! - index: Int! - from: String! - to: String! -} - -type ResultEvent { - block: _Block_! - tx: _Transaction_! - contract: String! - eventIndex: Int! - event: Event! - proof: Proof -} - -union Event = ApprovalEvent | ApprovalForAllEvent | TransferEvent - -type ApprovalEvent { - owner: String! - approved: String! - tokenId: BigInt! -} - -type ApprovalForAllEvent { - owner: String! - operator: String! - approved: Boolean! -} - -type TransferEvent { - from: String! - to: String! - tokenId: BigInt! -} - -type ResultState { - block: _Block_! - contractAddress: String! - cid: String! - kind: String! - data: String! -} - -type SyncStatus { - latestIndexedBlockHash: String! - latestIndexedBlockNumber: Int! - latestCanonicalBlockHash: String! - latestCanonicalBlockNumber: Int! -} - -type Query { - events(blockHash: String!, contractAddress: String!, name: String): [ResultEvent!] - eventsInRange(fromBlockNumber: Int!, toBlockNumber: Int!): [ResultEvent!] - supportsInterface(blockHash: String!, contractAddress: String!, interfaceId: String!): ResultBoolean! - balanceOf(blockHash: String!, contractAddress: String!, owner: String!): ResultBigInt! - ownerOf(blockHash: String!, contractAddress: String!, tokenId: BigInt!): ResultString! - getApproved(blockHash: String!, contractAddress: String!, tokenId: BigInt!): ResultString! - isApprovedForAll(blockHash: String!, contractAddress: String!, owner: String!, operator: String!): ResultBoolean! - name(blockHash: String!, contractAddress: String!): ResultString! - symbol(blockHash: String!, contractAddress: String!): ResultString! - tokenURI(blockHash: String!, contractAddress: String!, tokenId: BigInt!): ResultString! - _name(blockHash: String!, contractAddress: String!): ResultString! - _symbol(blockHash: String!, contractAddress: String!): ResultString! - _owners(blockHash: String!, contractAddress: String!, key0: BigInt!): ResultString! - _balances(blockHash: String!, contractAddress: String!, key0: String!): ResultBigInt! - _tokenApprovals(blockHash: String!, contractAddress: String!, key0: BigInt!): ResultString! - _operatorApprovals(blockHash: String!, contractAddress: String!, key0: String!, key1: String!): ResultBoolean! - getStateByCID(cid: String!): ResultState - getState(blockHash: String!, contractAddress: String!, kind: String): ResultState - getSyncStatus: SyncStatus - transferCount(id: String!, block: Block_height): TransferCount! -} - -type TransferCount { - id: ID! - count: Int! -} - -type Mutation { - watchContract(address: String!, kind: String!, checkpoint: Boolean!, startingBlock: Int): Boolean! -} - -type Subscription { - onEvent: ResultEvent! -} diff --git a/packages/erc721-watcher/src/server.ts b/packages/erc721-watcher/src/server.ts deleted file mode 100644 index a26bde87..00000000 --- a/packages/erc721-watcher/src/server.ts +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import fs from 'fs'; -import path from 'path'; -import 'reflect-metadata'; -import debug from 'debug'; - -import { ServerCmd } from '@cerc-io/cli'; - -import { createResolvers } from './resolvers'; -import { Indexer } from './indexer'; -import { Database } from './database'; - -const log = debug('vulcanize:server'); - -export const main = async (): Promise => { - const serverCmd = new ServerCmd(); - await serverCmd.init(Database); - await serverCmd.initIndexer(Indexer); - - const typeDefs = fs.readFileSync(path.join(__dirname, 'schema.gql')).toString(); - return serverCmd.exec(createResolvers, typeDefs); -}; - -main().then(() => { - log('Starting server...'); -}).catch(err => { - log(err); -}); diff --git a/packages/erc721-watcher/test/contracts/TestNFT.sol b/packages/erc721-watcher/test/contracts/TestNFT.sol deleted file mode 100644 index 0ebf59f6..00000000 --- a/packages/erc721-watcher/test/contracts/TestNFT.sol +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0 -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; - -contract TestNFT is ERC721 { - constructor() ERC721("TestNFT", "TNFT") { - } - - function mint(address to, uint256 tokenId) public { - _safeMint(to, tokenId); - } -} diff --git a/packages/erc721-watcher/test/tasks/account.ts b/packages/erc721-watcher/test/tasks/account.ts deleted file mode 100644 index 78a15e35..00000000 --- a/packages/erc721-watcher/test/tasks/account.ts +++ /dev/null @@ -1,12 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { task } from 'hardhat/config'; -import '@nomiclabs/hardhat-ethers'; - -task('account', 'Prints the account', async (taskArgs, hre) => { - const [account] = await hre.ethers.getSigners(); - - console.log(account.address); -}); diff --git a/packages/erc721-watcher/test/tasks/block-latest.ts b/packages/erc721-watcher/test/tasks/block-latest.ts deleted file mode 100644 index 0ba58bc7..00000000 --- a/packages/erc721-watcher/test/tasks/block-latest.ts +++ /dev/null @@ -1,18 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { task } from 'hardhat/config'; -import '@nomiclabs/hardhat-ethers'; - -task( - 'block-latest', - 'Prints the current block info', - async (_, { ethers }) => { - const blockNumber = await ethers.provider.getBlockNumber(); - const block = await ethers.provider.getBlock(blockNumber); - - console.log('Block Number:', blockNumber); - console.log('Block Hash:', block.hash); - } -); diff --git a/packages/erc721-watcher/test/tasks/nft-deploy.ts b/packages/erc721-watcher/test/tasks/nft-deploy.ts deleted file mode 100644 index 77838419..00000000 --- a/packages/erc721-watcher/test/tasks/nft-deploy.ts +++ /dev/null @@ -1,15 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { task } from 'hardhat/config'; -import '@nomiclabs/hardhat-ethers'; - -task('nft-deploy', 'Deploys NFT') - .setAction(async (args, hre) => { - await hre.run('compile'); - const NFT = await hre.ethers.getContractFactory('TestNFT'); - const nft = await NFT.deploy(); - - console.log('NFT deployed to:', nft.address); - }); diff --git a/packages/erc721-watcher/test/tasks/nft-mint.ts b/packages/erc721-watcher/test/tasks/nft-mint.ts deleted file mode 100644 index 03279491..00000000 --- a/packages/erc721-watcher/test/tasks/nft-mint.ts +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { task, types } from 'hardhat/config'; -import '@nomiclabs/hardhat-ethers'; -import { ContractTransaction } from 'ethers'; - -task('nft-mint', 'Mint NFT') - .addParam('nft', 'Contract address', undefined, types.string) - .addParam('tokenId', 'Token ID', undefined, types.string) - .addParam('to', 'Transfer recipient address', undefined, types.string) - .setAction(async (args, hre) => { - const { tokenId, to, nft: contractAddress } = args; - await hre.run('compile'); - const NFT = await hre.ethers.getContractFactory('TestNFT'); - const nft = NFT.attach(contractAddress); - - const transaction: ContractTransaction = await nft.mint(to, tokenId); - - const receipt = await transaction.wait(); - - if (receipt.events) { - const TransferEvent = receipt.events.find(el => el.event === 'Transfer'); - - if (TransferEvent && TransferEvent.args) { - console.log('Transfer Event'); - console.log('from:', TransferEvent.args.from.toString()); - console.log('to:', TransferEvent.args.to.toString()); - console.log('tokenId:', TransferEvent.args.tokenId.toString()); - } - } - }); diff --git a/packages/erc721-watcher/test/tasks/nft-transfer.ts b/packages/erc721-watcher/test/tasks/nft-transfer.ts deleted file mode 100644 index abca3484..00000000 --- a/packages/erc721-watcher/test/tasks/nft-transfer.ts +++ /dev/null @@ -1,34 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { task, types } from 'hardhat/config'; -import '@nomiclabs/hardhat-ethers'; -import { ContractTransaction } from 'ethers'; - -task('nft-transfer', 'Move tokens to recipient') - .addParam('nft', 'Contract address', undefined, types.string) - .addParam('from', 'Transfer from address', undefined, types.string) - .addParam('to', 'Transfer recipient address', undefined, types.string) - .addParam('tokenId', 'Token ID to transfer', undefined, types.string) - .setAction(async (args, hre) => { - const { nft: contractAddress, from, to, tokenId } = args; - await hre.run('compile'); - const NFT = await hre.ethers.getContractFactory('TestNFT'); - const nft = NFT.attach(contractAddress); - - const transaction: ContractTransaction = await nft['safeTransferFrom(address,address,uint256)'](from, to, tokenId); - - const receipt = await transaction.wait(); - - if (receipt.events) { - const TransferEvent = receipt.events.find(el => el.event === 'Transfer'); - - if (TransferEvent && TransferEvent.args) { - console.log('Transfer Event'); - console.log('from:', TransferEvent.args.from.toString()); - console.log('to:', TransferEvent.args.to.toString()); - console.log('tokenId:', TransferEvent.args.tokenId.toString()); - } - } - }); diff --git a/packages/erc721-watcher/tsconfig.json b/packages/erc721-watcher/tsconfig.json deleted file mode 100644 index 4e55bfd1..00000000 --- a/packages/erc721-watcher/tsconfig.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "compilerOptions": { - /* Visit https://aka.ms/tsconfig.json to read more about this file */ - - /* Basic Options */ - // "incremental": true, /* Enable incremental compilation */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ - "lib": ["es2019"], /* Specify library files to be included in the compilation. */ - // "allowJs": true, /* Allow javascript files to be compiled. */ - // "checkJs": true, /* Report errors in .js files. */ - // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ - // "declaration": true, /* Generates corresponding '.d.ts' file. */ - // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - "sourceMap": true, /* Generates corresponding '.map' file. */ - // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "dist", /* Redirect output structure to the directory. */ - // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - // "composite": true, /* Enable project compilation */ - // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ - // "removeComments": true, /* Do not emit comments to output. */ - // "noEmit": true, /* Do not emit outputs. */ - // "importHelpers": true, /* Import emit helpers from 'tslib'. */ - "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ - // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* Enable strict null checks. */ - // "strictFunctionTypes": true, /* Enable strict checking of function types. */ - // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ - // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ - // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - - /* Additional Checks */ - // "noUnusedLocals": true, /* Report errors on unused locals. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ - - /* Module Resolution Options */ - // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ - // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ - // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ - // "typeRoots": [], /* List of folders to include type definitions from. */ - // "types": [], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ - // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - - /* Source Map Options */ - // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ - // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - - /* Experimental Options */ - "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ - // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - - /* Advanced Options */ - "skipLibCheck": true, /* Skip type checking of declaration files. */ - "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ - "resolveJsonModule": true /* Enabling the option allows importing JSON, and validating the types in that JSON file. */ - }, - "include": ["src/**/*"] -} diff --git a/packages/graph-node/package.json b/packages/graph-node/package.json index c65a9480..89e905c4 100644 --- a/packages/graph-node/package.json +++ b/packages/graph-node/package.json @@ -11,6 +11,7 @@ "@nomiclabs/hardhat-waffle": "^2.0.1", "@types/chai": "^4.2.18", "@types/chai-spies": "^1.0.3", + "@types/lodash": "^4.14.168", "@types/pluralize": "^0.0.29", "@typescript-eslint/eslint-plugin": "^5.47.1", "@typescript-eslint/parser": "^5.47.1", @@ -54,6 +55,7 @@ "@cerc-io/ipld-eth-client": "^0.2.38", "@cerc-io/util": "^0.2.38", "@types/json-diff": "^0.5.2", + "@types/yargs": "^17.0.0", "bn.js": "^4.11.9", "debug": "^4.3.1", "fs-extra": "^10.0.0", diff --git a/packages/graph-test-watcher/.eslintignore b/packages/graph-test-watcher/.eslintignore deleted file mode 100644 index 55cb5225..00000000 --- a/packages/graph-test-watcher/.eslintignore +++ /dev/null @@ -1,2 +0,0 @@ -# Don't lint build output. -dist diff --git a/packages/graph-test-watcher/.eslintrc.json b/packages/graph-test-watcher/.eslintrc.json deleted file mode 100644 index a2b842c2..00000000 --- a/packages/graph-test-watcher/.eslintrc.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "env": { - "browser": true, - "es2021": true - }, - "extends": [ - "semistandard", - "plugin:@typescript-eslint/recommended" - ], - "parser": "@typescript-eslint/parser", - "parserOptions": { - "ecmaVersion": 12, - "sourceType": "module" - }, - "plugins": [ - "@typescript-eslint" - ], - "rules": { - "indent": ["error", 2, { "SwitchCase": 1 }], - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/explicit-module-boundary-types": [ - "warn", - { - "allowArgumentsExplicitlyTypedAsAny": true - } - ] - } -} diff --git a/packages/graph-test-watcher/.gitignore b/packages/graph-test-watcher/.gitignore deleted file mode 100644 index be541260..00000000 --- a/packages/graph-test-watcher/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -.idea/ -.vscode/ -node_modules/ -build/ -tmp/ -temp/ diff --git a/packages/graph-test-watcher/README.md b/packages/graph-test-watcher/README.md deleted file mode 100644 index 39debfe7..00000000 --- a/packages/graph-test-watcher/README.md +++ /dev/null @@ -1,141 +0,0 @@ -# Example Watcher - -## Setup - -First try the [stack orchestrator](https://github.com/cerc-io/stack-orchestrator) to quickly get started. Advanced users can see [here](/docs/README.md) for instructions on setting up a local environment by hand. - -Run the following command to install required packages: - -```bash -yarn -``` - -## Run - -* In [packages/graph-node](../graph-node/), deploy an `Example` contract: - - ```bash - yarn example:deploy - ``` - -* Set the returned address to the variable `$EXAMPLE_ADDRESS`: - - ```bash - EXAMPLE_ADDRESS= - ``` - -* In [packages/graph-node/test/subgraph/example1/subgraph.yaml](../graph-node/test/subgraph/example1/subgraph.yaml): - - * Set the source address for `Example1` datasource to the `EXAMPLE_ADDRESS`. - * Set the `startBlock` less than or equal to the latest mined block. - -* Build the example subgraph: - - ```bash - yarn build:example - ``` - -* Run the job-runner: - - ```bash - yarn job-runner - ``` - -* Run the watcher: - - ```bash - yarn server - ``` - -* The output from the block handler in the mapping code should be visible in the `job-runner` for each block. - -* Run the following GQL subscription at the graphql endpoint http://127.0.0.1:3008/graphql - - ```graphql - subscription { - onEvent { - event { - __typename - ... on TestEvent { - param1 - param2 - }, - }, - block { - number - hash - } - } - } - ``` - -* In [packages/graph-node](../graph-node/), trigger the `Test` event by calling a example contract method: - - ```bash - yarn example:test --address $EXAMPLE_ADDRESS - ``` - - * A `Test` event shall be visible in the subscription at endpoint. - - * The subgraph entity `Category` should be updated in the database. - - * An auto-generated `diff-staged` entry `State` should be added. - -* Run the query for entity in at the endpoint: - - ```graphql - query { - category( - block: { hash: "EVENT_BLOCK_HASH" }, - id: "1" - ) { - __typename - id - count - name - } - } - ``` - -* Run the `getState` query at the endpoint to get the latest `State` for `EXAMPLE_ADDRESS`: - - ```graphql - query { - getState ( - blockHash: "EVENT_BLOCK_HASH" - contractAddress: "EXAMPLE_ADDRESS" - # kind: "checkpoint" - # kind: "diff" - kind: "diff_staged" - ) { - cid - block { - cid - hash - number - timestamp - parentHash - } - contractAddress - data - } - } - ``` - -* `diff` states get created corresponding to the `diff_staged` states when their respective blocks reach the pruned region. - -* In [packages/graph-test-watcher](./): - - * After the `diff` state has been created, create a `checkpoint`: - - ```bash - yarn checkpoint create --address $EXAMPLE_ADDRESS - ``` - - * A `checkpoint` state should be created at the latest canonical block hash. - - * Run the `getState` query again at the endpoint with the output `blockHash` and kind `checkpoint`. - -* All the `State` entries can be seen in `pg-admin` in table `state`. - -* The existing example hooks in [hooks.ts](./src/hooks.ts) are for an `ERC20` contract. diff --git a/packages/graph-test-watcher/environments/local.toml b/packages/graph-test-watcher/environments/local.toml deleted file mode 100644 index 1ac82113..00000000 --- a/packages/graph-test-watcher/environments/local.toml +++ /dev/null @@ -1,72 +0,0 @@ -[server] - host = "127.0.0.1" - port = 3008 - kind = "active" - - # Checkpointing state. - checkpointing = true - - # Checkpoint interval in number of blocks. - checkpointInterval = 2000 - - # Enable state creation - enableState = true - - subgraphPath = "../graph-node/test/subgraph/example1/build" - wasmRestartBlocksInterval = 20 - - # Boolean to filter logs by contract. - filterLogs = false - - # Max block range for which to return events in eventsInRange GQL query. - # Use -1 for skipping check on block range. - maxEventsBlockRange = 1000 - - # Interval in number of blocks at which to clear entities cache. - clearEntitiesCacheInterval = 1000 - - # GQL cache settings - [server.gqlCache] - enabled = true - - # Max in-memory cache size (in bytes) (default 8 MB) - # maxCacheSize - - # GQL cache-control max-age settings (in seconds) - maxAge = 15 - timeTravelMaxAge = 86400 # 1 day - -[metrics] - host = "127.0.0.1" - port = 9000 - [metrics.gql] - port = 9001 - -[database] - type = "postgres" - host = "localhost" - port = 5432 - database = "graph-test-watcher" - username = "postgres" - password = "postgres" - synchronize = true - logging = false - -[upstream] - [upstream.ethServer] - gqlApiEndpoint = "http://127.0.0.1:8082/graphql" - rpcProviderEndpoint = "http://127.0.0.1:8081" - - [upstream.cache] - name = "requests" - enabled = false - deleteOnStart = false - -[jobQueue] - dbConnectionString = "postgres://postgres:postgres@localhost/graph-test-watcher-job-queue" - maxCompletionLagInSecs = 300 - jobDelayInMilliSecs = 100 - eventsInBatch = 50 - blockDelayInMilliSecs = 2000 - prefetchBlocksInMem = true - prefetchBlockCount = 10 diff --git a/packages/graph-test-watcher/package.json b/packages/graph-test-watcher/package.json deleted file mode 100644 index c3c0de33..00000000 --- a/packages/graph-test-watcher/package.json +++ /dev/null @@ -1,73 +0,0 @@ -{ - "name": "@cerc-io/graph-test-watcher", - "version": "0.2.38", - "description": "graph-test-watcher", - "private": true, - "main": "dist/index.js", - "scripts": { - "lint": "eslint .", - "build": "yarn clean && tsc && yarn copy-assets", - "clean": "rm -rf ./dist", - "copy-assets": "copyfiles -u 1 src/**/*.gql dist/", - "server": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true node --enable-source-maps dist/server.js", - "server:dev": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true ts-node src/server.ts", - "job-runner": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true node --enable-source-maps dist/job-runner.js", - "job-runner:dev": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true ts-node src/job-runner.ts", - "watch:contract": "DEBUG=vulcanize:* ts-node src/cli/watch-contract.ts", - "fill": "DEBUG=vulcanize:* ts-node src/fill.ts", - "fill:state": "DEBUG=vulcanize:* ts-node src/fill.ts --state", - "reset": "DEBUG=vulcanize:* ts-node src/cli/reset.ts", - "checkpoint": "DEBUG=vulcanize:* node --enable-source-maps dist/cli/checkpoint.js", - "checkpoint:dev": "DEBUG=vulcanize:* ts-node src/cli/checkpoint.ts", - "export-state": "DEBUG=vulcanize:* node --enable-source-maps dist/cli/export-state.js", - "export-state:dev": "DEBUG=vulcanize:* ts-node src/cli/export-state.ts", - "import-state": "DEBUG=vulcanize:* node --enable-source-maps dist/cli/import-state.js", - "import-state:dev": "DEBUG=vulcanize:* ts-node src/cli/import-state.ts", - "inspect-cid": "DEBUG=vulcanize:* ts-node src/cli/inspect-cid.ts", - "index-block": "DEBUG=vulcanize:* ts-node src/cli/index-block.ts" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/cerc-io/watcher-ts.git" - }, - "author": "", - "license": "AGPL-3.0", - "bugs": { - "url": "https://github.com/cerc-io/watcher-ts/issues" - }, - "homepage": "https://github.com/cerc-io/watcher-ts#readme", - "dependencies": { - "@apollo/client": "^3.3.19", - "@cerc-io/cli": "^0.2.38", - "@cerc-io/graph-node": "^0.2.38", - "@cerc-io/ipld-eth-client": "^0.2.38", - "@cerc-io/solidity-mapper": "^0.2.38", - "@cerc-io/util": "^0.2.38", - "@ethersproject/providers": "^5.4.4", - "apollo-type-bigint": "^0.1.3", - "debug": "^4.3.1", - "decimal.js": "^10.3.1", - "ethers": "^5.4.4", - "graphql": "^15.5.0", - "json-bigint": "^1.0.0", - "reflect-metadata": "^0.1.13", - "typeorm": "^0.2.32", - "yargs": "^17.0.1" - }, - "devDependencies": { - "@ethersproject/abi": "^5.3.0", - "@types/yargs": "^17.0.0", - "@typescript-eslint/eslint-plugin": "^5.47.1", - "@typescript-eslint/parser": "^5.47.1", - "copyfiles": "^2.4.1", - "eslint": "^8.35.0", - "eslint-config-semistandard": "^15.0.1", - "eslint-config-standard": "^16.0.3", - "eslint-plugin-import": "^2.27.5", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-promise": "^5.1.0", - "eslint-plugin-standard": "^5.0.0", - "ts-node": "^10.2.1", - "typescript": "^5.0.2" - } -} diff --git a/packages/graph-test-watcher/src/artifacts/Example.json b/packages/graph-test-watcher/src/artifacts/Example.json deleted file mode 100644 index 294f2acc..00000000 --- a/packages/graph-test-watcher/src/artifacts/Example.json +++ /dev/null @@ -1,134 +0,0 @@ -{ - "abi": [ - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "string", - "name": "param1", - "type": "string" - }, - { - "indexed": false, - "internalType": "uint8", - "name": "param2", - "type": "uint8" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "param3", - "type": "uint256" - } - ], - "name": "Test", - "type": "event" - }, - { - "inputs": [ - { - "internalType": "uint128", - "name": "bidAmount1", - "type": "uint128" - }, - { - "internalType": "uint128", - "name": "bidAmount2", - "type": "uint128" - } - ], - "name": "addMethod", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [], - "name": "emitEvent", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "getMethod", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint128", - "name": "bidAmount1", - "type": "uint128" - }, - { - "internalType": "uint128", - "name": "bidAmount2", - "type": "uint128" - } - ], - "name": "structMethod", - "outputs": [ - { - "components": [ - { - "internalType": "uint128", - "name": "bidAmount1", - "type": "uint128" - }, - { - "internalType": "uint128", - "name": "bidAmount2", - "type": "uint128" - } - ], - "internalType": "struct Example.Bid", - "name": "", - "type": "tuple" - } - ], - "stateMutability": "pure", - "type": "function" - } - ], - "storageLayout": { - "storage": [ - { - "astId": 3, - "contract": "Example.sol:Example", - "label": "_test", - "offset": 0, - "slot": "0", - "type": "t_uint256" - } - ], - "types": { - "t_uint256": { - "encoding": "inplace", - "label": "uint256", - "numberOfBytes": "32" - } - } - } -} \ No newline at end of file diff --git a/packages/graph-test-watcher/src/cli/checkpoint-cmds/create.ts b/packages/graph-test-watcher/src/cli/checkpoint-cmds/create.ts deleted file mode 100644 index e771c702..00000000 --- a/packages/graph-test-watcher/src/cli/checkpoint-cmds/create.ts +++ /dev/null @@ -1,44 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { CreateCheckpointCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from '../../database'; -import { Indexer } from '../../indexer'; - -export const command = 'create'; - -export const desc = 'Create checkpoint'; - -export const builder = { - address: { - type: 'string', - require: true, - demandOption: true, - describe: 'Contract address to create the checkpoint for.' - }, - blockHash: { - type: 'string', - describe: 'Blockhash at which to create the checkpoint.' - } -}; - -export const handler = async (argv: any): Promise => { - const createCheckpointCmd = new CreateCheckpointCmd(); - await createCheckpointCmd.init(argv, Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - createCheckpointCmd.config.server, - createCheckpointCmd.clients.ethClient, - createCheckpointCmd.ethProvider, - createCheckpointCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await createCheckpointCmd.initIndexer(Indexer, graphWatcher); - - await createCheckpointCmd.exec(); -}; diff --git a/packages/graph-test-watcher/src/cli/checkpoint-cmds/verify.ts b/packages/graph-test-watcher/src/cli/checkpoint-cmds/verify.ts deleted file mode 100644 index 3709f543..00000000 --- a/packages/graph-test-watcher/src/cli/checkpoint-cmds/verify.ts +++ /dev/null @@ -1,40 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { VerifyCheckpointCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from '../../database'; -import { Indexer } from '../../indexer'; - -export const command = 'verify'; - -export const desc = 'Verify checkpoint'; - -export const builder = { - cid: { - type: 'string', - alias: 'c', - demandOption: true, - describe: 'Checkpoint CID to be verified' - } -}; - -export const handler = async (argv: any): Promise => { - const verifyCheckpointCmd = new VerifyCheckpointCmd(); - await verifyCheckpointCmd.init(argv, Database); - - const { graphWatcher, graphDb } = await getGraphDbAndWatcher( - verifyCheckpointCmd.config.server, - verifyCheckpointCmd.clients.ethClient, - verifyCheckpointCmd.ethProvider, - verifyCheckpointCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await verifyCheckpointCmd.initIndexer(Indexer, graphWatcher); - - await verifyCheckpointCmd.exec(graphDb); -}; diff --git a/packages/graph-test-watcher/src/cli/checkpoint.ts b/packages/graph-test-watcher/src/cli/checkpoint.ts deleted file mode 100644 index d05ad8ad..00000000 --- a/packages/graph-test-watcher/src/cli/checkpoint.ts +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import yargs from 'yargs'; -import 'reflect-metadata'; -import debug from 'debug'; - -import { DEFAULT_CONFIG_PATH } from '@cerc-io/util'; - -import { hideBin } from 'yargs/helpers'; - -const log = debug('vulcanize:checkpoint'); - -const main = async () => { - return yargs(hideBin(process.argv)) - .parserConfiguration({ - 'parse-numbers': false - }).options({ - configFile: { - alias: 'f', - type: 'string', - require: true, - demandOption: true, - describe: 'configuration file path (toml)', - default: DEFAULT_CONFIG_PATH - } - }) - .commandDir('checkpoint-cmds', { extensions: ['ts', 'js'], exclude: /([a-zA-Z0-9\s_\\.\-:])+(.d.ts)$/ }) - .demandCommand(1) - .help() - .argv; -}; - -main().then(() => { - process.exit(); -}).catch(err => { - log(err); -}); diff --git a/packages/graph-test-watcher/src/cli/export-state.ts b/packages/graph-test-watcher/src/cli/export-state.ts deleted file mode 100644 index bcd1c8ab..00000000 --- a/packages/graph-test-watcher/src/cli/export-state.ts +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { ExportStateCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:export-state'); - -const main = async (): Promise => { - const exportStateCmd = new ExportStateCmd(); - await exportStateCmd.init(Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - exportStateCmd.config.server, - exportStateCmd.clients.ethClient, - exportStateCmd.ethProvider, - exportStateCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await exportStateCmd.initIndexer(Indexer, graphWatcher); - - await exportStateCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/graph-test-watcher/src/cli/import-state.ts b/packages/graph-test-watcher/src/cli/import-state.ts deleted file mode 100644 index 04ce0e8c..00000000 --- a/packages/graph-test-watcher/src/cli/import-state.ts +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { ImportStateCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from '../database'; -import { Indexer } from '../indexer'; -import { State } from '../entity/State'; - -const log = debug('vulcanize:import-state'); - -export const main = async (): Promise => { - const importStateCmd = new ImportStateCmd(); - await importStateCmd.init(Database); - - const { graphWatcher, graphDb } = await getGraphDbAndWatcher( - importStateCmd.config.server, - importStateCmd.clients.ethClient, - importStateCmd.ethProvider, - importStateCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await importStateCmd.initIndexer(Indexer, graphWatcher); - - await importStateCmd.exec(State, graphDb); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/graph-test-watcher/src/cli/index-block.ts b/packages/graph-test-watcher/src/cli/index-block.ts deleted file mode 100644 index 19a302af..00000000 --- a/packages/graph-test-watcher/src/cli/index-block.ts +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { IndexBlockCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:index-block'); - -const main = async (): Promise => { - const indexBlockCmd = new IndexBlockCmd(); - await indexBlockCmd.init(Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - indexBlockCmd.config.server, - indexBlockCmd.clients.ethClient, - indexBlockCmd.ethProvider, - indexBlockCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await indexBlockCmd.initIndexer(Indexer, graphWatcher); - - await indexBlockCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/graph-test-watcher/src/cli/inspect-cid.ts b/packages/graph-test-watcher/src/cli/inspect-cid.ts deleted file mode 100644 index 4f5955ef..00000000 --- a/packages/graph-test-watcher/src/cli/inspect-cid.ts +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { InspectCIDCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:inspect-cid'); - -const main = async (): Promise => { - const inspectCIDCmd = new InspectCIDCmd(); - await inspectCIDCmd.init(Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - inspectCIDCmd.config.server, - inspectCIDCmd.clients.ethClient, - inspectCIDCmd.ethProvider, - inspectCIDCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await inspectCIDCmd.initIndexer(Indexer, graphWatcher); - - await inspectCIDCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/graph-test-watcher/src/cli/reset-cmds/job-queue.ts b/packages/graph-test-watcher/src/cli/reset-cmds/job-queue.ts deleted file mode 100644 index c33cbfd6..00000000 --- a/packages/graph-test-watcher/src/cli/reset-cmds/job-queue.ts +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import debug from 'debug'; - -import { getConfig, resetJobs, Config } from '@cerc-io/util'; - -const log = debug('vulcanize:reset-job-queue'); - -export const command = 'job-queue'; - -export const desc = 'Reset job queue'; - -export const builder = {}; - -export const handler = async (argv: any): Promise => { - const config: Config = await getConfig(argv.configFile); - await resetJobs(config); - - log('Job queue reset successfully'); -}; diff --git a/packages/graph-test-watcher/src/cli/reset-cmds/state.ts b/packages/graph-test-watcher/src/cli/reset-cmds/state.ts deleted file mode 100644 index 33211d6e..00000000 --- a/packages/graph-test-watcher/src/cli/reset-cmds/state.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { ResetStateCmd } from '@cerc-io/cli'; - -import { Database } from '../../database'; - -export const command = 'state'; - -export const desc = 'Reset State to a given block number'; - -export const builder = { - blockNumber: { - type: 'number' - } -}; - -export const handler = async (argv: any): Promise => { - const resetStateCmd = new ResetStateCmd(); - await resetStateCmd.init(argv, Database); - - await resetStateCmd.exec(); -}; diff --git a/packages/graph-test-watcher/src/cli/reset-cmds/watcher.ts b/packages/graph-test-watcher/src/cli/reset-cmds/watcher.ts deleted file mode 100644 index 827fd28d..00000000 --- a/packages/graph-test-watcher/src/cli/reset-cmds/watcher.ts +++ /dev/null @@ -1,37 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { ResetWatcherCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from '../../database'; -import { Indexer } from '../../indexer'; - -export const command = 'watcher'; - -export const desc = 'Reset watcher to a block number'; - -export const builder = { - blockNumber: { - type: 'number' - } -}; - -export const handler = async (argv: any): Promise => { - const resetWatcherCmd = new ResetWatcherCmd(); - await resetWatcherCmd.init(argv, Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - resetWatcherCmd.config.server, - resetWatcherCmd.clients.ethClient, - resetWatcherCmd.ethProvider, - resetWatcherCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await resetWatcherCmd.initIndexer(Indexer, graphWatcher); - - await resetWatcherCmd.exec(); -}; diff --git a/packages/graph-test-watcher/src/cli/reset.ts b/packages/graph-test-watcher/src/cli/reset.ts deleted file mode 100644 index 95648c88..00000000 --- a/packages/graph-test-watcher/src/cli/reset.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { getResetYargs } from '@cerc-io/util'; - -const log = debug('vulcanize:reset'); - -const main = async () => { - return getResetYargs() - .commandDir('reset-cmds', { extensions: ['ts', 'js'], exclude: /([a-zA-Z0-9\s_\\.\-:])+(.d.ts)$/ }) - .demandCommand(1) - .help() - .argv; -}; - -main().then(() => { - process.exit(); -}).catch(err => { - log(err); -}); diff --git a/packages/graph-test-watcher/src/cli/watch-contract.ts b/packages/graph-test-watcher/src/cli/watch-contract.ts deleted file mode 100644 index 7d6ce1a5..00000000 --- a/packages/graph-test-watcher/src/cli/watch-contract.ts +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { WatchContractCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:watch-contract'); - -const main = async (): Promise => { - const watchContractCmd = new WatchContractCmd(); - await watchContractCmd.init(Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - watchContractCmd.config.server, - watchContractCmd.clients.ethClient, - watchContractCmd.ethProvider, - watchContractCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await watchContractCmd.initIndexer(Indexer, graphWatcher); - - await watchContractCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/graph-test-watcher/src/client.ts b/packages/graph-test-watcher/src/client.ts deleted file mode 100644 index 16aad813..00000000 --- a/packages/graph-test-watcher/src/client.ts +++ /dev/null @@ -1,73 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { gql } from '@apollo/client/core'; -import { GraphQLClient, GraphQLConfig } from '@cerc-io/ipld-eth-client'; - -import { queries, mutations, subscriptions } from './gql'; - -export class Client { - _config: GraphQLConfig; - _client: GraphQLClient; - - constructor (config: GraphQLConfig) { - this._config = config; - - this._client = new GraphQLClient(config); - } - - async getGetMethod (blockHash: string, contractAddress: string): Promise { - const { getMethod } = await this._client.query( - gql(queries.getMethod), - { blockHash, contractAddress } - ); - - return getMethod; - } - - async _getTest (blockHash: string, contractAddress: string): Promise { - const { _test } = await this._client.query( - gql(queries._test), - { blockHash, contractAddress } - ); - - return _test; - } - - async getEvents (blockHash: string, contractAddress: string, name: string): Promise { - const { events } = await this._client.query( - gql(queries.events), - { blockHash, contractAddress, name } - ); - - return events; - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise { - const { eventsInRange } = await this._client.query( - gql(queries.eventsInRange), - { fromBlockNumber, toBlockNumber } - ); - - return eventsInRange; - } - - async watchContract (contractAddress: string, startingBlock?: number): Promise { - const { watchContract } = await this._client.mutate( - gql(mutations.watchContract), - { contractAddress, startingBlock } - ); - - return watchContract; - } - - async watchEvents (onNext: (value: any) => void): Promise { - return this._client.subscribe( - gql(subscriptions.onEvent), - ({ data }) => { - onNext(data.onEvent); - } - ); - } -} diff --git a/packages/graph-test-watcher/src/database.ts b/packages/graph-test-watcher/src/database.ts deleted file mode 100644 index a2584a90..00000000 --- a/packages/graph-test-watcher/src/database.ts +++ /dev/null @@ -1,297 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import { Connection, ConnectionOptions, DeepPartial, FindConditions, QueryRunner, FindManyOptions, EntityTarget } from 'typeorm'; -import path from 'path'; - -import { Database as BaseDatabase, DatabaseInterface, QueryOptions, StateKind, Where } from '@cerc-io/util'; - -import { Contract } from './entity/Contract'; -import { Event } from './entity/Event'; -import { SyncStatus } from './entity/SyncStatus'; -import { StateSyncStatus } from './entity/StateSyncStatus'; -import { BlockProgress } from './entity/BlockProgress'; -import { State } from './entity/State'; - -import { GetMethod } from './entity/GetMethod'; -import { _Test } from './entity/_Test'; -import { Author } from './entity/Author'; -import { Blog } from './entity/Blog'; -import { Category } from './entity/Category'; - -export const SUBGRAPH_ENTITIES = new Set([Author, Blog, Category]); -export const ENTITIES = [_Test, GetMethod, ...SUBGRAPH_ENTITIES]; -export const ENTITY_TO_LATEST_ENTITY_MAP: Map = new Map(); -export const ENTITY_QUERY_TYPE_MAP = new Map(); - -export class Database implements DatabaseInterface { - _config: ConnectionOptions; - _conn!: Connection; - _baseDatabase: BaseDatabase; - _propColMaps: { [key: string]: Map; }; - - constructor (config: ConnectionOptions) { - assert(config); - - this._config = { - ...config, - entities: [path.join(__dirname, 'entity/*')], - subscribers: [path.join(__dirname, 'entity/Subscriber.*')] - }; - - this._baseDatabase = new BaseDatabase(this._config); - this._propColMaps = {}; - } - - get baseDatabase (): BaseDatabase { - return this._baseDatabase; - } - - async init (): Promise { - this._conn = await this._baseDatabase.init(); - this._setPropColMaps(); - } - - async close (): Promise { - return this._baseDatabase.close(); - } - - async getGetMethod ({ blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise { - return this._conn.getRepository(GetMethod) - .findOne({ - blockHash, - contractAddress - }); - } - - async _getTest ({ blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise<_Test | undefined> { - return this._conn.getRepository(_Test) - .findOne({ - blockHash, - contractAddress - }); - } - - async saveGetMethod ({ blockHash, blockNumber, contractAddress, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(GetMethod); - const entity = repo.create({ blockHash, blockNumber, contractAddress, value, proof }); - return repo.save(entity); - } - - async _saveTest ({ blockHash, blockNumber, contractAddress, value, proof }: DeepPartial<_Test>): Promise<_Test> { - const repo = this._conn.getRepository(_Test); - const entity = repo.create({ blockHash, blockNumber, contractAddress, value, proof }); - return repo.save(entity); - } - - getNewState (): State { - return new State(); - } - - async getStates (where: FindConditions): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getStates(repo, where); - } - - async getLatestState (contractAddress: string, kind: StateKind | null, blockNumber?: number): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getLatestState(repo, contractAddress, kind, blockNumber); - } - - async getPrevState (blockHash: string, contractAddress: string, kind?: string): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getPrevState(repo, blockHash, contractAddress, kind); - } - - // Fetch all diff States after the specified block number. - async getDiffStatesInRange (contractAddress: string, startblock: number, endBlock: number): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getDiffStatesInRange(repo, contractAddress, startblock, endBlock); - } - - async saveOrUpdateState (dbTx: QueryRunner, state: State): Promise { - const repo = dbTx.manager.getRepository(State); - - return this._baseDatabase.saveOrUpdateState(repo, state); - } - - async removeStates (dbTx: QueryRunner, blockNumber: number, kind: string): Promise { - const repo = dbTx.manager.getRepository(State); - - await this._baseDatabase.removeStates(repo, blockNumber, kind); - } - - async removeStatesAfterBlock (dbTx: QueryRunner, blockNumber: number): Promise { - const repo = dbTx.manager.getRepository(State); - - await this._baseDatabase.removeStatesAfterBlock(repo, blockNumber); - } - - async getStateSyncStatus (): Promise { - const repo = this._conn.getRepository(StateSyncStatus); - - return this._baseDatabase.getStateSyncStatus(repo); - } - - async updateStateSyncStatusIndexedBlock (queryRunner: QueryRunner, blockNumber: number, force?: boolean): Promise { - const repo = queryRunner.manager.getRepository(StateSyncStatus); - - return this._baseDatabase.updateStateSyncStatusIndexedBlock(repo, blockNumber, force); - } - - async updateStateSyncStatusCheckpointBlock (queryRunner: QueryRunner, blockNumber: number, force?: boolean): Promise { - const repo = queryRunner.manager.getRepository(StateSyncStatus); - - return this._baseDatabase.updateStateSyncStatusCheckpointBlock(repo, blockNumber, force); - } - - async getContracts (): Promise { - const repo = this._conn.getRepository(Contract); - - return this._baseDatabase.getContracts(repo); - } - - async createTransactionRunner (): Promise { - return this._baseDatabase.createTransactionRunner(); - } - - async getProcessedBlockCountForRange (fromBlockNumber: number, toBlockNumber: number): Promise<{ expected: number, actual: number }> { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getProcessedBlockCountForRange(repo, fromBlockNumber, toBlockNumber); - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise> { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getEventsInRange(repo, fromBlockNumber, toBlockNumber); - } - - async saveEventEntity (queryRunner: QueryRunner, entity: Event): Promise { - const repo = queryRunner.manager.getRepository(Event); - return this._baseDatabase.saveEventEntity(repo, entity); - } - - async getBlockEvents (blockHash: string, where: Where, queryOptions: QueryOptions): Promise { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getBlockEvents(repo, blockHash, where, queryOptions); - } - - async saveBlockWithEvents (queryRunner: QueryRunner, block: DeepPartial, events: DeepPartial[]): Promise { - const blockRepo = queryRunner.manager.getRepository(BlockProgress); - const eventRepo = queryRunner.manager.getRepository(Event); - - return this._baseDatabase.saveBlockWithEvents(blockRepo, eventRepo, block, events); - } - - async saveEvents (queryRunner: QueryRunner, events: Event[]): Promise { - const eventRepo = queryRunner.manager.getRepository(Event); - - return this._baseDatabase.saveEvents(eventRepo, events); - } - - async saveBlockProgress (queryRunner: QueryRunner, block: DeepPartial): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.saveBlockProgress(repo, block); - } - - async saveContract (queryRunner: QueryRunner, address: string, kind: string, checkpoint: boolean, startingBlock: number): Promise { - const repo = queryRunner.manager.getRepository(Contract); - - return this._baseDatabase.saveContract(repo, address, kind, checkpoint, startingBlock); - } - - async updateSyncStatusIndexedBlock (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusIndexedBlock(repo, blockHash, blockNumber, force); - } - - async updateSyncStatusCanonicalBlock (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusCanonicalBlock(repo, blockHash, blockNumber, force); - } - - async updateSyncStatusChainHead (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusChainHead(repo, blockHash, blockNumber, force); - } - - async getSyncStatus (queryRunner: QueryRunner): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.getSyncStatus(repo); - } - - async getEvent (id: string): Promise { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getEvent(repo, id); - } - - async getBlocksAtHeight (height: number, isPruned: boolean): Promise { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getBlocksAtHeight(repo, height, isPruned); - } - - async markBlocksAsPruned (queryRunner: QueryRunner, blocks: BlockProgress[]): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.markBlocksAsPruned(repo, blocks); - } - - async getBlockProgress (blockHash: string): Promise { - const repo = this._conn.getRepository(BlockProgress); - return this._baseDatabase.getBlockProgress(repo, blockHash); - } - - async getBlockProgressEntities (where: FindConditions, options: FindManyOptions): Promise { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getBlockProgressEntities(repo, where, options); - } - - async getEntitiesForBlock (blockHash: string, tableName: string): Promise { - return this._baseDatabase.getEntitiesForBlock(blockHash, tableName); - } - - async updateBlockProgress (queryRunner: QueryRunner, block: BlockProgress, lastProcessedEventIndex: number): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.updateBlockProgress(repo, block, lastProcessedEventIndex); - } - - async removeEntities (queryRunner: QueryRunner, entity: new () => Entity, findConditions?: FindManyOptions | FindConditions): Promise { - return this._baseDatabase.removeEntities(queryRunner, entity, findConditions); - } - - async deleteEntitiesByConditions (queryRunner: QueryRunner, entity: EntityTarget, findConditions: FindConditions): Promise { - await this._baseDatabase.deleteEntitiesByConditions(queryRunner, entity, findConditions); - } - - async getAncestorAtDepth (blockHash: string, depth: number): Promise { - return this._baseDatabase.getAncestorAtDepth(blockHash, depth); - } - - _getPropertyColumnMapForEntity (entityName: string): Map { - return this._conn.getMetadata(entityName).ownColumns.reduce((acc, curr) => { - return acc.set(curr.propertyName, curr.databaseName); - }, new Map()); - } - - _setPropColMaps (): void { - this._propColMaps.GetMethod = this._getPropertyColumnMapForEntity('GetMethod'); - this._propColMaps._Test = this._getPropertyColumnMapForEntity('_Test'); - } -} diff --git a/packages/graph-test-watcher/src/entity/Author.ts b/packages/graph-test-watcher/src/entity/Author.ts deleted file mode 100644 index 2305c926..00000000 --- a/packages/graph-test-watcher/src/entity/Author.ts +++ /dev/null @@ -1,42 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; -import Decimal from 'decimal.js'; - -import { bigintTransformer, decimalTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockNumber']) -export class Author { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('numeric', { transformer: bigintTransformer }) - blogCount!: bigint; - - @Column('varchar') - name!: string; - - @Column('integer') - paramInt!: number; - - @Column('numeric', { transformer: bigintTransformer }) - paramBigInt!: bigint; - - @Column('varchar') - paramBytes!: string; - - @Column('numeric', { default: 0, transformer: decimalTransformer }) - rating!: Decimal; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/graph-test-watcher/src/entity/BlockProgress.ts b/packages/graph-test-watcher/src/entity/BlockProgress.ts deleted file mode 100644 index e744aae4..00000000 --- a/packages/graph-test-watcher/src/entity/BlockProgress.ts +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, CreateDateColumn } from 'typeorm'; -import { BlockProgressInterface } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash'], { unique: true }) -@Index(['blockNumber']) -@Index(['parentHash']) -export class BlockProgress implements BlockProgressInterface { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar') - cid!: string; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('varchar', { length: 66 }) - parentHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('integer') - blockTimestamp!: number; - - @Column('integer') - numEvents!: number; - - @Column('integer') - numProcessedEvents!: number; - - @Column('integer') - lastProcessedEventIndex!: number; - - @Column('boolean') - isComplete!: boolean; - - @Column('boolean', { default: false }) - isPruned!: boolean; - - @CreateDateColumn() - createdAt!: Date; -} diff --git a/packages/graph-test-watcher/src/entity/Blog.ts b/packages/graph-test-watcher/src/entity/Blog.ts deleted file mode 100644 index dd5dad64..00000000 --- a/packages/graph-test-watcher/src/entity/Blog.ts +++ /dev/null @@ -1,47 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; - -import { bigintArrayTransformer } from '@cerc-io/util'; - -enum BlogType { - short = 'short', - long = 'long' -} - -@Entity() -@Index(['blockNumber']) -export class Blog { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column({ - type: 'enum', - enum: BlogType, - default: BlogType.short - }) - kind!: BlogType; - - @Column('boolean') - isActive!: boolean; - - @Column('numeric', { transformer: bigintArrayTransformer, array: true }) - reviews!: bigint[]; - - @Column('varchar') - author!: string; - - @Column('varchar', { array: true }) - categories!: string[]; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/graph-test-watcher/src/entity/Category.ts b/packages/graph-test-watcher/src/entity/Category.ts deleted file mode 100644 index e2e5681b..00000000 --- a/packages/graph-test-watcher/src/entity/Category.ts +++ /dev/null @@ -1,29 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; - -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockNumber']) -export class Category { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('numeric', { transformer: bigintTransformer }) - count!: bigint; - - @Column('varchar') - name!: string; - - @Column('boolean', { default: false }) - isPruned!: boolean; -} diff --git a/packages/graph-test-watcher/src/entity/Contract.ts b/packages/graph-test-watcher/src/entity/Contract.ts deleted file mode 100644 index de66b387..00000000 --- a/packages/graph-test-watcher/src/entity/Contract.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['address'], { unique: true }) -export class Contract { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 42 }) - address!: string; - - @Column('varchar') - kind!: string; - - @Column('boolean') - checkpoint!: boolean; - - @Column('integer') - startingBlock!: number; -} diff --git a/packages/graph-test-watcher/src/entity/Event.ts b/packages/graph-test-watcher/src/entity/Event.ts deleted file mode 100644 index 91f1e6d3..00000000 --- a/packages/graph-test-watcher/src/entity/Event.ts +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, ManyToOne } from 'typeorm'; -import { BlockProgress } from './BlockProgress'; - -@Entity() -@Index(['block', 'contract']) -@Index(['block', 'contract', 'eventName']) -export class Event { - @PrimaryGeneratedColumn() - id!: number; - - @ManyToOne(() => BlockProgress, { onDelete: 'CASCADE' }) - block!: BlockProgress; - - @Column('varchar', { length: 66 }) - txHash!: string; - - @Column('integer') - index!: number; - - @Column('varchar', { length: 42 }) - contract!: string; - - @Column('varchar', { length: 256 }) - eventName!: string; - - @Column('text') - eventInfo!: string; - - @Column('text') - extraInfo!: string; - - @Column('text') - proof!: string; -} diff --git a/packages/graph-test-watcher/src/entity/FrothyEntity.ts b/packages/graph-test-watcher/src/entity/FrothyEntity.ts deleted file mode 100644 index dbbbab7b..00000000 --- a/packages/graph-test-watcher/src/entity/FrothyEntity.ts +++ /dev/null @@ -1,21 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { Entity, PrimaryColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockNumber']) -export class FrothyEntity { - @PrimaryColumn('varchar') - id!: string; - - @PrimaryColumn('varchar') - name!: string; - - @PrimaryColumn('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; -} diff --git a/packages/graph-test-watcher/src/entity/GetMethod.ts b/packages/graph-test-watcher/src/entity/GetMethod.ts deleted file mode 100644 index dbe9bafb..00000000 --- a/packages/graph-test-watcher/src/entity/GetMethod.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockHash', 'contractAddress'], { unique: true }) -export class GetMethod { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - value!: string; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/graph-test-watcher/src/entity/State.ts b/packages/graph-test-watcher/src/entity/State.ts deleted file mode 100644 index 10ef261e..00000000 --- a/packages/graph-test-watcher/src/entity/State.ts +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, ManyToOne } from 'typeorm'; - -import { StateKind } from '@cerc-io/util'; - -import { BlockProgress } from './BlockProgress'; - -@Entity() -@Index(['cid'], { unique: true }) -@Index(['block', 'contractAddress']) -@Index(['block', 'contractAddress', 'kind'], { unique: true }) -export class State { - @PrimaryGeneratedColumn() - id!: number; - - @ManyToOne(() => BlockProgress, { onDelete: 'CASCADE' }) - block!: BlockProgress; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - cid!: string; - - @Column({ - type: 'enum', - enum: StateKind - }) - kind!: StateKind; - - @Column('bytea') - data!: Buffer; -} diff --git a/packages/graph-test-watcher/src/entity/StateSyncStatus.ts b/packages/graph-test-watcher/src/entity/StateSyncStatus.ts deleted file mode 100644 index c795212f..00000000 --- a/packages/graph-test-watcher/src/entity/StateSyncStatus.ts +++ /dev/null @@ -1,17 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; - -@Entity() -export class StateSyncStatus { - @PrimaryGeneratedColumn() - id!: number; - - @Column('integer') - latestIndexedBlockNumber!: number; - - @Column('integer', { nullable: true }) - latestCheckpointBlockNumber!: number; -} diff --git a/packages/graph-test-watcher/src/entity/Subscriber.ts b/packages/graph-test-watcher/src/entity/Subscriber.ts deleted file mode 100644 index 2cccb841..00000000 --- a/packages/graph-test-watcher/src/entity/Subscriber.ts +++ /dev/null @@ -1,21 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { EventSubscriber, EntitySubscriberInterface, InsertEvent, UpdateEvent } from 'typeorm'; - -import { afterEntityInsertOrUpdate } from '@cerc-io/util'; - -import { FrothyEntity } from './FrothyEntity'; -import { ENTITY_TO_LATEST_ENTITY_MAP, SUBGRAPH_ENTITIES } from '../database'; - -@EventSubscriber() -export class EntitySubscriber implements EntitySubscriberInterface { - async afterInsert (event: InsertEvent): Promise { - await afterEntityInsertOrUpdate(FrothyEntity, SUBGRAPH_ENTITIES, event, ENTITY_TO_LATEST_ENTITY_MAP); - } - - async afterUpdate (event: UpdateEvent): Promise { - await afterEntityInsertOrUpdate(FrothyEntity, SUBGRAPH_ENTITIES, event, ENTITY_TO_LATEST_ENTITY_MAP); - } -} diff --git a/packages/graph-test-watcher/src/entity/SyncStatus.ts b/packages/graph-test-watcher/src/entity/SyncStatus.ts deleted file mode 100644 index 19d0dfa7..00000000 --- a/packages/graph-test-watcher/src/entity/SyncStatus.ts +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; -import { SyncStatusInterface } from '@cerc-io/util'; - -@Entity() -export class SyncStatus implements SyncStatusInterface { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - chainHeadBlockHash!: string; - - @Column('integer') - chainHeadBlockNumber!: number; - - @Column('varchar', { length: 66 }) - latestIndexedBlockHash!: string; - - @Column('integer') - latestIndexedBlockNumber!: number; - - @Column('varchar', { length: 66 }) - latestCanonicalBlockHash!: string; - - @Column('integer') - latestCanonicalBlockNumber!: number; - - @Column('varchar', { length: 66 }) - initialIndexedBlockHash!: string; - - @Column('integer') - initialIndexedBlockNumber!: number; -} diff --git a/packages/graph-test-watcher/src/entity/_Test.ts b/packages/graph-test-watcher/src/entity/_Test.ts deleted file mode 100644 index 3a8fd170..00000000 --- a/packages/graph-test-watcher/src/entity/_Test.ts +++ /dev/null @@ -1,28 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash', 'contractAddress'], { unique: true }) -export class _Test { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('numeric', { transformer: bigintTransformer }) - value!: bigint; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/graph-test-watcher/src/fill.ts b/packages/graph-test-watcher/src/fill.ts deleted file mode 100644 index a09ea2b4..00000000 --- a/packages/graph-test-watcher/src/fill.ts +++ /dev/null @@ -1,43 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { FillCmd } from '@cerc-io/cli'; -import { getContractEntitiesMap } from '@cerc-io/util'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from './database'; -import { Indexer } from './indexer'; - -const log = debug('vulcanize:fill'); - -export const main = async (): Promise => { - const fillCmd = new FillCmd(); - await fillCmd.init(Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - fillCmd.config.server, - fillCmd.clients.ethClient, - fillCmd.ethProvider, - fillCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await fillCmd.initIndexer(Indexer, graphWatcher); - - // Get contractEntitiesMap required for fill-state - // NOTE: Assuming each entity type is only mapped to a single contract - const contractEntitiesMap = getContractEntitiesMap(graphWatcher.dataSources); - - await fillCmd.exec(contractEntitiesMap); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(); -}); diff --git a/packages/graph-test-watcher/src/gql/index.ts b/packages/graph-test-watcher/src/gql/index.ts deleted file mode 100644 index 4732f682..00000000 --- a/packages/graph-test-watcher/src/gql/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * as mutations from './mutations'; -export * as queries from './queries'; -export * as subscriptions from './subscriptions'; diff --git a/packages/graph-test-watcher/src/gql/mutations/index.ts b/packages/graph-test-watcher/src/gql/mutations/index.ts deleted file mode 100644 index 0c3bd853..00000000 --- a/packages/graph-test-watcher/src/gql/mutations/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -import fs from 'fs'; -import path from 'path'; - -export const watchContract = fs.readFileSync(path.join(__dirname, 'watchContract.gql'), 'utf8'); diff --git a/packages/graph-test-watcher/src/gql/mutations/watchContract.gql b/packages/graph-test-watcher/src/gql/mutations/watchContract.gql deleted file mode 100644 index 2ecc74f7..00000000 --- a/packages/graph-test-watcher/src/gql/mutations/watchContract.gql +++ /dev/null @@ -1,3 +0,0 @@ -mutation watchContract($address: String!, $kind: String!, $checkpoint: Boolean!, $startingBlock: Int){ - watchContract(address: $address, kind: $kind, checkpoint: $checkpoint, startingBlock: $startingBlock) -} \ No newline at end of file diff --git a/packages/graph-test-watcher/src/gql/queries/_test.gql b/packages/graph-test-watcher/src/gql/queries/_test.gql deleted file mode 100644 index b6ac4407..00000000 --- a/packages/graph-test-watcher/src/gql/queries/_test.gql +++ /dev/null @@ -1,8 +0,0 @@ -query _test($blockHash: String!, $contractAddress: String!){ - _test(blockHash: $blockHash, contractAddress: $contractAddress){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/graph-test-watcher/src/gql/queries/author.gql b/packages/graph-test-watcher/src/gql/queries/author.gql deleted file mode 100644 index ff3644df..00000000 --- a/packages/graph-test-watcher/src/gql/queries/author.gql +++ /dev/null @@ -1,16 +0,0 @@ -query author($id: String!, $blockHash: Bytes!){ - author(id: $id, block: { hash: $blockHash }){ - id - blogCount - name - rating - paramInt - paramBytes - blogs { - id - kind - reviews - isActive - } - } -} diff --git a/packages/graph-test-watcher/src/gql/queries/blog.gql b/packages/graph-test-watcher/src/gql/queries/blog.gql deleted file mode 100644 index 313ca9fc..00000000 --- a/packages/graph-test-watcher/src/gql/queries/blog.gql +++ /dev/null @@ -1,17 +0,0 @@ -query blog($id: String!, $blockHash: Bytes!){ - blog(id: $id, block: { hash: $blockHash }){ - id - kind - reviews - isActive - author { - id - name - } - categories { - id - name - count - } - } -} diff --git a/packages/graph-test-watcher/src/gql/queries/category.gql b/packages/graph-test-watcher/src/gql/queries/category.gql deleted file mode 100644 index d3e24e23..00000000 --- a/packages/graph-test-watcher/src/gql/queries/category.gql +++ /dev/null @@ -1,7 +0,0 @@ -query category($id: String!, $blockHash: Bytes!){ - category(id: $id, block: { hash: $blockHash }){ - id - count - name - } -} diff --git a/packages/graph-test-watcher/src/gql/queries/events.gql b/packages/graph-test-watcher/src/gql/queries/events.gql deleted file mode 100644 index de52299c..00000000 --- a/packages/graph-test-watcher/src/gql/queries/events.gql +++ /dev/null @@ -1,28 +0,0 @@ -query events($blockHash: String!, $contractAddress: String!, $name: String){ - events(blockHash: $blockHash, contractAddress: $contractAddress, name: $name){ - block{ - cid - hash - number - timestamp - parentHash - } - tx{ - hash - index - from - to - } - contract - eventIndex - event{ - ... on TestEvent { - param1 - param2 - } - } - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/graph-test-watcher/src/gql/queries/eventsInRange.gql b/packages/graph-test-watcher/src/gql/queries/eventsInRange.gql deleted file mode 100644 index ebfa9572..00000000 --- a/packages/graph-test-watcher/src/gql/queries/eventsInRange.gql +++ /dev/null @@ -1,28 +0,0 @@ -query eventsInRange($fromBlockNumber: Int!, $toBlockNumber: Int!){ - eventsInRange(fromBlockNumber: $fromBlockNumber, toBlockNumber: $toBlockNumber){ - block{ - cid - hash - number - timestamp - parentHash - } - tx{ - hash - index - from - to - } - contract - eventIndex - event{ - ... on TestEvent { - param1 - param2 - } - } - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/graph-test-watcher/src/gql/queries/getMethod.gql b/packages/graph-test-watcher/src/gql/queries/getMethod.gql deleted file mode 100644 index c02c4896..00000000 --- a/packages/graph-test-watcher/src/gql/queries/getMethod.gql +++ /dev/null @@ -1,8 +0,0 @@ -query getMethod($blockHash: String!, $contractAddress: String!){ - getMethod(blockHash: $blockHash, contractAddress: $contractAddress){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/graph-test-watcher/src/gql/queries/getState.gql b/packages/graph-test-watcher/src/gql/queries/getState.gql deleted file mode 100644 index 3b8f6050..00000000 --- a/packages/graph-test-watcher/src/gql/queries/getState.gql +++ /dev/null @@ -1,15 +0,0 @@ -query getState($blockHash: String!, $contractAddress: String!, $kind: String){ - getState(blockHash: $blockHash, contractAddress: $contractAddress, kind: $kind){ - block{ - cid - hash - number - timestamp - parentHash - } - contractAddress - cid - kind - data - } -} \ No newline at end of file diff --git a/packages/graph-test-watcher/src/gql/queries/getStateByCID.gql b/packages/graph-test-watcher/src/gql/queries/getStateByCID.gql deleted file mode 100644 index 6c3c4fd8..00000000 --- a/packages/graph-test-watcher/src/gql/queries/getStateByCID.gql +++ /dev/null @@ -1,15 +0,0 @@ -query getStateByCID($cid: String!){ - getStateByCID(cid: $cid){ - block{ - cid - hash - number - timestamp - parentHash - } - contractAddress - cid - kind - data - } -} \ No newline at end of file diff --git a/packages/graph-test-watcher/src/gql/queries/index.ts b/packages/graph-test-watcher/src/gql/queries/index.ts deleted file mode 100644 index e5838f0e..00000000 --- a/packages/graph-test-watcher/src/gql/queries/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -import fs from 'fs'; -import path from 'path'; - -export const events = fs.readFileSync(path.join(__dirname, 'events.gql'), 'utf8'); -export const eventsInRange = fs.readFileSync(path.join(__dirname, 'eventsInRange.gql'), 'utf8'); -export const getMethod = fs.readFileSync(path.join(__dirname, 'getMethod.gql'), 'utf8'); -export const _test = fs.readFileSync(path.join(__dirname, '_test.gql'), 'utf8'); -export const exampleEntity = fs.readFileSync(path.join(__dirname, 'exampleEntity.gql'), 'utf8'); -export const getStateByCID = fs.readFileSync(path.join(__dirname, 'getStateByCID.gql'), 'utf8'); -export const getState = fs.readFileSync(path.join(__dirname, 'getState.gql'), 'utf8'); diff --git a/packages/graph-test-watcher/src/gql/subscriptions/index.ts b/packages/graph-test-watcher/src/gql/subscriptions/index.ts deleted file mode 100644 index f12910c5..00000000 --- a/packages/graph-test-watcher/src/gql/subscriptions/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -import fs from 'fs'; -import path from 'path'; - -export const onEvent = fs.readFileSync(path.join(__dirname, 'onEvent.gql'), 'utf8'); diff --git a/packages/graph-test-watcher/src/gql/subscriptions/onEvent.gql b/packages/graph-test-watcher/src/gql/subscriptions/onEvent.gql deleted file mode 100644 index 57f3b509..00000000 --- a/packages/graph-test-watcher/src/gql/subscriptions/onEvent.gql +++ /dev/null @@ -1,28 +0,0 @@ -subscription onEvent{ - onEvent{ - block{ - cid - hash - number - timestamp - parentHash - } - tx{ - hash - index - from - to - } - contract - eventIndex - event{ - ... on TestEvent { - param1 - param2 - } - } - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/graph-test-watcher/src/hooks.ts b/packages/graph-test-watcher/src/hooks.ts deleted file mode 100644 index e727296e..00000000 --- a/packages/graph-test-watcher/src/hooks.ts +++ /dev/null @@ -1,69 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; - -import { ResultEvent } from '@cerc-io/util'; - -import { Indexer } from './indexer'; - -/** - * Hook function to store an initial state. - * @param indexer Indexer instance. - * @param blockHash Hash of the concerned block. - * @param contractAddress Address of the concerned contract. - * @returns Data block to be stored. - */ -export async function createInitialState (indexer: Indexer, contractAddress: string, blockHash: string): Promise { - assert(indexer); - assert(blockHash); - assert(contractAddress); - - // Store an empty State. - const stateData: any = { - state: {} - }; - - // Return initial state data to be saved. - return stateData; -} - -/** - * Hook function to create state diff. - * @param indexer Indexer instance that contains methods to fetch the contract varaiable values. - * @param blockHash Block hash of the concerned block. - */ -export async function createStateDiff (indexer: Indexer, blockHash: string): Promise { - assert(indexer); - assert(blockHash); - - // Use indexer.createDiff() method to save custom state diff(s). -} - -/** - * Hook function to create state checkpoint - * @param indexer Indexer instance. - * @param contractAddress Address of the concerned contract. - * @param blockHash Block hash of the concerned block. - * @returns Whether to disable default checkpoint. If false, the state from this hook is updated with that from default checkpoint. - */ -export async function createStateCheckpoint (indexer: Indexer, contractAddress: string, blockHash: string): Promise { - assert(indexer); - assert(blockHash); - assert(contractAddress); - - // Use indexer.createStateCheckpoint() method to create a custom checkpoint. - - return false; -} - -/** - * Event hook function. - * @param indexer Indexer instance that contains methods to fetch and update the contract values in the database. - * @param eventData ResultEvent object containing event information. - */ -export async function handleEvent (indexer: Indexer, eventData: ResultEvent): Promise { - assert(indexer); - assert(eventData); -} diff --git a/packages/graph-test-watcher/src/indexer.ts b/packages/graph-test-watcher/src/indexer.ts deleted file mode 100644 index b2ccc06f..00000000 --- a/packages/graph-test-watcher/src/indexer.ts +++ /dev/null @@ -1,676 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import debug from 'debug'; -import { DeepPartial, FindConditions, FindManyOptions, ObjectLiteral } from 'typeorm'; -import JSONbig from 'json-bigint'; -import { ethers } from 'ethers'; -import { SelectionNode } from 'graphql'; - -import { JsonFragment } from '@ethersproject/abi'; -import { BaseProvider } from '@ethersproject/providers'; -import { EthClient } from '@cerc-io/ipld-eth-client'; -import { StorageLayout, MappingKey } from '@cerc-io/solidity-mapper'; -import { - Indexer as BaseIndexer, - ValueResult, - ServerConfig, - updateStateForElementaryType, - JobQueue, - Where, - QueryOptions, - BlockHeight, - StateKind, - IndexerInterface, - StateStatus, - ResultEvent, - getResultEvent, - DatabaseInterface, - Clients, - GraphWatcherInterface, - updateSubgraphState, - dumpSubgraphState -} from '@cerc-io/util'; -import { GraphWatcher } from '@cerc-io/graph-node'; - -import { Database, ENTITIES, SUBGRAPH_ENTITIES } from './database'; -import { Contract } from './entity/Contract'; -import { Event } from './entity/Event'; -import { SyncStatus } from './entity/SyncStatus'; -import { StateSyncStatus } from './entity/StateSyncStatus'; -import { BlockProgress } from './entity/BlockProgress'; -import { State } from './entity/State'; -import Example1Artifacts from './artifacts/Example.json'; -import { createInitialState, handleEvent, createStateDiff, createStateCheckpoint } from './hooks'; -import { Author } from './entity/Author'; -import { Blog } from './entity/Blog'; -import { Category } from './entity/Category'; -import { FrothyEntity } from './entity/FrothyEntity'; - -const log = debug('vulcanize:indexer'); -const JSONbigNative = JSONbig({ useNativeBigInt: true }); - -const KIND_EXAMPLE1 = 'Example1'; - -export class Indexer implements IndexerInterface { - _db: Database; - _ethClient: EthClient; - _ethProvider: BaseProvider; - _baseIndexer: BaseIndexer; - _serverConfig: ServerConfig; - _graphWatcher: GraphWatcher; - - _abiMap: Map; - _storageLayoutMap: Map; - _contractMap: Map; - - _entityTypesMap: Map; - _relationsMap: Map; - - _subgraphStateMap: Map; - - constructor (serverConfig: ServerConfig, db: DatabaseInterface, clients: Clients, ethProvider: BaseProvider, jobQueue: JobQueue, graphWatcher?: GraphWatcherInterface) { - assert(db); - assert(clients.ethClient); - - this._db = db as Database; - this._ethClient = clients.ethClient; - this._ethProvider = ethProvider; - this._serverConfig = serverConfig; - this._baseIndexer = new BaseIndexer(this._serverConfig, this._db, this._ethClient, this._ethProvider, jobQueue); - - assert(graphWatcher); - this._graphWatcher = graphWatcher as GraphWatcher; - - this._abiMap = new Map(); - this._storageLayoutMap = new Map(); - this._contractMap = new Map(); - - const { - abi: Example1ABI, - storageLayout: Example1StorageLayout - } = Example1Artifacts; - - assert(Example1ABI); - assert(Example1StorageLayout); - this._abiMap.set(KIND_EXAMPLE1, Example1ABI); - this._storageLayoutMap.set(KIND_EXAMPLE1, Example1StorageLayout); - this._contractMap.set(KIND_EXAMPLE1, new ethers.utils.Interface(Example1ABI)); - - this._entityTypesMap = new Map(); - this._populateEntityTypesMap(); - - this._relationsMap = new Map(); - this._populateRelationsMap(); - - this._subgraphStateMap = new Map(); - } - - get serverConfig (): ServerConfig { - return this._serverConfig; - } - - get storageLayoutMap (): Map { - return this._storageLayoutMap; - } - - get graphWatcher (): GraphWatcher { - return this._graphWatcher; - } - - async init (): Promise { - await this._baseIndexer.fetchContracts(); - await this._baseIndexer.fetchStateStatus(); - } - - getResultEvent (event: Event): ResultEvent { - return getResultEvent(event); - } - - async getMethod (blockHash: string, contractAddress: string): Promise { - const entity = await this._db.getGetMethod({ blockHash, contractAddress }); - if (entity) { - log('getMethod: db hit.'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('getMethod: db miss, fetching from upstream server'); - - const { block: { number } } = await this._ethClient.getBlockByHash(blockHash); - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - const abi = this._abiMap.get(KIND_EXAMPLE1); - assert(abi); - - const contract = new ethers.Contract(contractAddress, abi, this._ethProvider); - const value = await contract.getMethod({ blockTag: blockHash }); - - const result: ValueResult = { value }; - - await this._db.saveGetMethod({ blockHash, blockNumber, contractAddress, value: result.value, proof: JSONbigNative.stringify(result.proof) }); - - return result; - } - - async _test (blockHash: string, contractAddress: string, diff = false): Promise { - const entity = await this._db._getTest({ blockHash, contractAddress }); - if (entity) { - log('_test: db hit.'); - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - log('_test: db miss, fetching from upstream server'); - - const { block: { number } } = await this._ethClient.getBlockByHash(blockHash); - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - const storageLayout = this._storageLayoutMap.get(KIND_EXAMPLE1); - assert(storageLayout); - - const result = await this._baseIndexer.getStorageValue( - storageLayout, - blockHash, - contractAddress, - '_test' - ); - - await this._db._saveTest({ blockHash, blockNumber, contractAddress, value: result.value, proof: JSONbigNative.stringify(result.proof) }); - - if (diff) { - const stateUpdate = updateStateForElementaryType({}, '_test', result.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - - return result; - } - - async getStorageValue (storageLayout: StorageLayout, blockHash: string, contractAddress: string, variable: string, ...mappingKeys: MappingKey[]): Promise { - return this._baseIndexer.getStorageValue( - storageLayout, - blockHash, - contractAddress, - variable, - ...mappingKeys - ); - } - - async getEntitiesForBlock (blockHash: string, tableName: string): Promise { - return this._db.getEntitiesForBlock(blockHash, tableName); - } - - async processInitialState (contractAddress: string, blockHash: string): Promise { - // Call initial state hook. - return createInitialState(this, contractAddress, blockHash); - } - - async processStateCheckpoint (contractAddress: string, blockHash: string): Promise { - // Call checkpoint hook. - return createStateCheckpoint(this, contractAddress, blockHash); - } - - async processCanonicalBlock (blockHash: string, blockNumber: number): Promise { - console.time('time:indexer#processCanonicalBlock-finalize_auto_diffs'); - // Finalize staged diff blocks if any. - await this._baseIndexer.finalizeDiffStaged(blockHash); - console.timeEnd('time:indexer#processCanonicalBlock-finalize_auto_diffs'); - - // Call custom stateDiff hook. - await createStateDiff(this, blockHash); - - this._graphWatcher.pruneEntityCacheFrothyBlocks(blockHash, blockNumber); - } - - async processCheckpoint (blockHash: string): Promise { - // Return if checkpointInterval is <= 0. - const checkpointInterval = this._serverConfig.checkpointInterval; - if (checkpointInterval <= 0) return; - - console.time('time:indexer#processCheckpoint-checkpoint'); - await this._baseIndexer.processCheckpoint(this, blockHash, checkpointInterval); - console.timeEnd('time:indexer#processCheckpoint-checkpoint'); - } - - async processCLICheckpoint (contractAddress: string, blockHash?: string): Promise { - return this._baseIndexer.processCLICheckpoint(this, contractAddress, blockHash); - } - - async getPrevState (blockHash: string, contractAddress: string, kind?: string): Promise { - return this._db.getPrevState(blockHash, contractAddress, kind); - } - - async getLatestState (contractAddress: string, kind: StateKind | null, blockNumber?: number): Promise { - return this._db.getLatestState(contractAddress, kind, blockNumber); - } - - async getStatesByHash (blockHash: string): Promise { - return this._baseIndexer.getStatesByHash(blockHash); - } - - async getStateByCID (cid: string): Promise { - return this._baseIndexer.getStateByCID(cid); - } - - async getStates (where: FindConditions): Promise { - return this._db.getStates(where); - } - - getStateData (state: State): any { - return this._baseIndexer.getStateData(state); - } - - // Method used to create auto diffs (diff_staged). - async createDiffStaged (contractAddress: string, blockHash: string, data: any): Promise { - console.time('time:indexer#createDiffStaged-auto_diff'); - await this._baseIndexer.createDiffStaged(contractAddress, blockHash, data); - console.timeEnd('time:indexer#createDiffStaged-auto_diff'); - } - - // Method to be used by createStateDiff hook. - async createDiff (contractAddress: string, blockHash: string, data: any): Promise { - const block = await this.getBlockProgress(blockHash); - assert(block); - - await this._baseIndexer.createDiff(contractAddress, block, data); - } - - // Method to be used by createStateCheckpoint hook. - async createStateCheckpoint (contractAddress: string, blockHash: string, data: any): Promise { - const block = await this.getBlockProgress(blockHash); - assert(block); - - return this._baseIndexer.createStateCheckpoint(contractAddress, block, data); - } - - // Method to be used by export-state CLI. - async createCheckpoint (contractAddress: string, blockHash: string): Promise { - const block = await this.getBlockProgress(blockHash); - assert(block); - - return this._baseIndexer.createCheckpoint(this, contractAddress, block); - } - - // Method to be used by fill-state CLI. - async createInit (blockHash: string, blockNumber: number): Promise { - // Create initial state for contracts. - await this._baseIndexer.createInit(this, blockHash, blockNumber); - } - - async saveOrUpdateState (state: State): Promise { - return this._baseIndexer.saveOrUpdateState(state); - } - - async removeStates (blockNumber: number, kind: StateKind): Promise { - await this._baseIndexer.removeStates(blockNumber, kind); - } - - async getSubgraphEntity ( - entity: new () => Entity, - id: string, - block: BlockHeight, - selections: ReadonlyArray = [] - ): Promise { - const data = await this._graphWatcher.getEntity(entity, id, this._relationsMap, block, selections); - - return data; - } - - async getSubgraphEntities ( - entity: new () => Entity, - block: BlockHeight, - where: { [key: string]: any } = {}, - queryOptions: QueryOptions = {}, - selections: ReadonlyArray = [] - ): Promise { - return this._graphWatcher.getEntities(entity, this._relationsMap, block, where, queryOptions, selections); - } - - async triggerIndexingOnEvent (event: Event): Promise { - const resultEvent = this.getResultEvent(event); - - console.time('time:indexer#processEvent-mapping_code'); - // Call subgraph handler for event. - await this._graphWatcher.handleEvent(resultEvent); - console.timeEnd('time:indexer#processEvent-mapping_code'); - - // Call custom hook function for indexing on event. - await handleEvent(this, resultEvent); - } - - async processEvent (event: Event): Promise { - // Trigger indexing of data based on the event. - await this.triggerIndexingOnEvent(event); - } - - async processBlock (blockProgress: BlockProgress): Promise { - console.time('time:indexer#processBlock-init_state'); - // Call a function to create initial state for contracts. - await this._baseIndexer.createInit(this, blockProgress.blockHash, blockProgress.blockNumber); - console.timeEnd('time:indexer#processBlock-init_state'); - - this._graphWatcher.updateEntityCacheFrothyBlocks(blockProgress); - } - - async processBlockAfterEvents (blockHash: string, blockNumber: number): Promise { - console.time('time:indexer#processBlockAfterEvents-mapping_code'); - // Call subgraph handler for block. - await this._graphWatcher.handleBlock(blockHash, blockNumber); - console.timeEnd('time:indexer#processBlockAfterEvents-mapping_code'); - - console.time('time:indexer#processBlockAfterEvents-dump_subgraph_state'); - // Persist subgraph state to the DB. - await this.dumpSubgraphState(blockHash); - console.timeEnd('time:indexer#processBlockAfterEvents-dump_subgraph_state'); - } - - parseEventNameAndArgs (kind: string, logObj: any): any { - const { topics, data } = logObj; - - const contract = this._contractMap.get(kind); - assert(contract); - - const logDescription = contract.parseLog({ data, topics }); - - const { eventName, eventInfo, eventSignature } = this._baseIndexer.parseEvent(logDescription); - - return { - eventName, - eventInfo, - eventSignature - }; - } - - async getStateSyncStatus (): Promise { - return this._db.getStateSyncStatus(); - } - - async updateStateSyncStatusIndexedBlock (blockNumber: number, force?: boolean): Promise { - const dbTx = await this._db.createTransactionRunner(); - let res; - - try { - res = await this._db.updateStateSyncStatusIndexedBlock(dbTx, blockNumber, force); - await dbTx.commitTransaction(); - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - - return res; - } - - async updateStateSyncStatusCheckpointBlock (blockNumber: number, force?: boolean): Promise { - const dbTx = await this._db.createTransactionRunner(); - let res; - - try { - res = await this._db.updateStateSyncStatusCheckpointBlock(dbTx, blockNumber, force); - await dbTx.commitTransaction(); - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - - return res; - } - - async getLatestCanonicalBlock (): Promise { - const syncStatus = await this.getSyncStatus(); - assert(syncStatus); - - const latestCanonicalBlock = await this.getBlockProgress(syncStatus.latestCanonicalBlockHash); - assert(latestCanonicalBlock); - - return latestCanonicalBlock; - } - - async getLatestStateIndexedBlock (): Promise { - return this._baseIndexer.getLatestStateIndexedBlock(); - } - - async addContracts (): Promise { - // Watching all the contracts in the subgraph. - await this._graphWatcher.addContracts(); - } - - async watchContract (address: string, kind: string, checkpoint: boolean, startingBlock: number): Promise { - return this._baseIndexer.watchContract(address, kind, checkpoint, startingBlock); - } - - updateStateStatusMap (address: string, stateStatus: StateStatus): void { - this._baseIndexer.updateStateStatusMap(address, stateStatus); - } - - cacheContract (contract: Contract): void { - return this._baseIndexer.cacheContract(contract); - } - - async saveEventEntity (dbEvent: Event): Promise { - return this._baseIndexer.saveEventEntity(dbEvent); - } - - async getEventsByFilter (blockHash: string, contract?: string, name?: string): Promise> { - return this._baseIndexer.getEventsByFilter(blockHash, contract, name); - } - - isWatchedContract (address : string): Contract | undefined { - return this._baseIndexer.isWatchedContract(address); - } - - getContractsByKind (kind: string): Contract[] { - return this._baseIndexer.getContractsByKind(kind); - } - - async getProcessedBlockCountForRange (fromBlockNumber: number, toBlockNumber: number): Promise<{ expected: number, actual: number }> { - return this._baseIndexer.getProcessedBlockCountForRange(fromBlockNumber, toBlockNumber); - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise> { - return this._baseIndexer.getEventsInRange(fromBlockNumber, toBlockNumber, this._serverConfig.maxEventsBlockRange); - } - - async getSyncStatus (): Promise { - return this._baseIndexer.getSyncStatus(); - } - - async getBlocks (blockFilter: { blockHash?: string, blockNumber?: number }): Promise { - return this._baseIndexer.getBlocks(blockFilter); - } - - async updateSyncStatusIndexedBlock (blockHash: string, blockNumber: number, force = false): Promise { - return this._baseIndexer.updateSyncStatusIndexedBlock(blockHash, blockNumber, force); - } - - async updateSyncStatusChainHead (blockHash: string, blockNumber: number, force = false): Promise { - return this._baseIndexer.updateSyncStatusChainHead(blockHash, blockNumber, force); - } - - async updateSyncStatusCanonicalBlock (blockHash: string, blockNumber: number, force = false): Promise { - const syncStatus = this._baseIndexer.updateSyncStatusCanonicalBlock(blockHash, blockNumber, force); - await this.pruneFrothyEntities(blockNumber); - - return syncStatus; - } - - async getEvent (id: string): Promise { - return this._baseIndexer.getEvent(id); - } - - async getBlockProgress (blockHash: string): Promise { - return this._baseIndexer.getBlockProgress(blockHash); - } - - async getBlockProgressEntities (where: FindConditions, options: FindManyOptions): Promise { - return this._baseIndexer.getBlockProgressEntities(where, options); - } - - async getBlocksAtHeight (height: number, isPruned: boolean): Promise { - return this._baseIndexer.getBlocksAtHeight(height, isPruned); - } - - async saveBlockAndFetchEvents (block: DeepPartial): Promise<[BlockProgress, DeepPartial[]]> { - return this._saveBlockAndFetchEvents(block); - } - - async getBlockEvents (blockHash: string, where: Where, queryOptions: QueryOptions): Promise> { - return this._baseIndexer.getBlockEvents(blockHash, where, queryOptions); - } - - async removeUnknownEvents (block: BlockProgress): Promise { - return this._baseIndexer.removeUnknownEvents(Event, block); - } - - async markBlocksAsPruned (blocks: BlockProgress[]): Promise { - await this._baseIndexer.markBlocksAsPruned(blocks); - - await this._graphWatcher.pruneEntities(FrothyEntity, blocks, SUBGRAPH_ENTITIES); - } - - async pruneFrothyEntities (blockNumber: number): Promise { - await this._graphWatcher.pruneFrothyEntities(FrothyEntity, blockNumber); - } - - async resetLatestEntities (blockNumber: number): Promise { - await this._graphWatcher.resetLatestEntities(blockNumber); - } - - async updateBlockProgress (block: BlockProgress, lastProcessedEventIndex: number): Promise { - return this._baseIndexer.updateBlockProgress(block, lastProcessedEventIndex); - } - - async getAncestorAtDepth (blockHash: string, depth: number): Promise { - return this._baseIndexer.getAncestorAtDepth(blockHash, depth); - } - - getEntityTypesMap (): Map { - return this._entityTypesMap; - } - - getRelationsMap (): Map { - return this._relationsMap; - } - - updateSubgraphState (contractAddress: string, data: any): void { - return updateSubgraphState(this._subgraphStateMap, contractAddress, data); - } - - async dumpSubgraphState (blockHash: string, isStateFinalized = false): Promise { - return dumpSubgraphState(this, this._subgraphStateMap, blockHash, isStateFinalized); - } - - async resetWatcherToBlock (blockNumber: number): Promise { - const entities = [...ENTITIES, FrothyEntity]; - await this._baseIndexer.resetWatcherToBlock(blockNumber, entities); - - await this.resetLatestEntities(blockNumber); - } - - _populateEntityTypesMap (): void { - this._entityTypesMap.set( - 'Author', - { - id: 'ID', - blogCount: 'BigInt', - name: 'String', - rating: 'BigDecimal', - paramInt: 'Int', - paramBigInt: 'BigInt', - paramBytes: 'Bytes' - } - ); - - this._entityTypesMap.set( - 'Blog', - { - id: 'ID', - kind: 'BlogKind', - isActive: 'Boolean', - reviews: 'BigInt', - author: 'Author', - categories: 'Category' - } - ); - - this._entityTypesMap.set( - 'Category', - { - id: 'ID', - name: 'String', - count: 'BigInt' - } - ); - } - - _populateRelationsMap (): void { - this._relationsMap.set(Author, { - blogs: { - entity: Blog, - isDerived: true, - isArray: true, - field: 'author' - } - }); - - this._relationsMap.set(Blog, { - author: { - entity: Author, - isDerived: false, - isArray: false - }, - categories: { - entity: Category, - isDerived: false, - isArray: true - } - }); - } - - async _saveBlockAndFetchEvents ({ - cid: blockCid, - blockHash, - blockNumber, - blockTimestamp, - parentHash - }: DeepPartial): Promise<[BlockProgress, DeepPartial[]]> { - assert(blockHash); - assert(blockNumber); - - const dbEvents = await this._baseIndexer.fetchEvents(blockHash, blockNumber, this.parseEventNameAndArgs.bind(this)); - - const dbTx = await this._db.createTransactionRunner(); - try { - const block = { - cid: blockCid, - blockHash, - blockNumber, - blockTimestamp, - parentHash - }; - - console.time(`time:indexer#_saveBlockAndFetchEvents-db-save-${blockNumber}`); - const blockProgress = await this._db.saveBlockWithEvents(dbTx, block, dbEvents); - await dbTx.commitTransaction(); - console.timeEnd(`time:indexer#_saveBlockAndFetchEvents-db-save-${blockNumber}`); - - return [blockProgress, []]; - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - } -} diff --git a/packages/graph-test-watcher/src/job-runner.ts b/packages/graph-test-watcher/src/job-runner.ts deleted file mode 100644 index 84b0065e..00000000 --- a/packages/graph-test-watcher/src/job-runner.ts +++ /dev/null @@ -1,47 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import debug from 'debug'; - -import { JobRunnerCmd } from '@cerc-io/cli'; -import { JobRunner } from '@cerc-io/util'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { Indexer } from './indexer'; -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from './database'; - -const log = debug('vulcanize:job-runner'); - -export const main = async (): Promise => { - const jobRunnerCmd = new JobRunnerCmd(); - await jobRunnerCmd.init(Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - jobRunnerCmd.config.server, - jobRunnerCmd.clients.ethClient, - jobRunnerCmd.ethProvider, - jobRunnerCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await jobRunnerCmd.initIndexer(Indexer, graphWatcher); - - await jobRunnerCmd.exec(async (jobRunner: JobRunner): Promise => { - await jobRunner.subscribeBlockProcessingQueue(); - await jobRunner.subscribeEventProcessingQueue(); - await jobRunner.subscribeBlockCheckpointQueue(); - await jobRunner.subscribeHooksQueue(); - }); -}; - -main().then(() => { - log('Starting job runner...'); -}).catch(err => { - log(err); -}); - -process.on('uncaughtException', err => { - log('uncaughtException', err); -}); diff --git a/packages/graph-test-watcher/src/resolvers.ts b/packages/graph-test-watcher/src/resolvers.ts deleted file mode 100644 index b80ea97a..00000000 --- a/packages/graph-test-watcher/src/resolvers.ts +++ /dev/null @@ -1,200 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import BigInt from 'apollo-type-bigint'; -import debug from 'debug'; -import Decimal from 'decimal.js'; -import { GraphQLResolveInfo, GraphQLScalarType } from 'graphql'; - -import { - ValueResult, - BlockHeight, - gqlTotalQueryCount, - gqlQueryCount, - jsonBigIntStringReplacer, - getResultState, - setGQLCacheHints, - IndexerInterface, - EventWatcher -} from '@cerc-io/util'; - -import { Indexer } from './indexer'; - -import { Author } from './entity/Author'; -import { Blog } from './entity/Blog'; -import { Category } from './entity/Category'; - -const log = debug('vulcanize:resolver'); - -export const createResolvers = async (indexerArg: IndexerInterface, eventWatcher: EventWatcher): Promise => { - const indexer = indexerArg as Indexer; - - const gqlCacheConfig = indexer.serverConfig.gqlCache; - - return { - BigInt: new BigInt('bigInt'), - - BigDecimal: new GraphQLScalarType({ - name: 'BigDecimal', - description: 'BigDecimal custom scalar type', - parseValue (value) { - // value from the client - return new Decimal(value); - }, - serialize (value: Decimal) { - // value sent to the client - return value.toFixed(); - } - }), - - Event: { - __resolveType: (obj: any) => { - assert(obj.__typename); - - return obj.__typename; - } - }, - - Subscription: { - onEvent: { - subscribe: () => eventWatcher.getEventIterator() - } - }, - - Mutation: { - watchContract: async (_: any, { address, kind, checkpoint, startingBlock = 1 }: { address: string, kind: string, checkpoint: boolean, startingBlock: number }): Promise => { - log('watchContract', address, kind, checkpoint, startingBlock); - await indexer.watchContract(address, kind, checkpoint, startingBlock); - - return true; - } - }, - - Query: { - getMethod: (_: any, { blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise => { - log('getMethod', blockHash, contractAddress); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('getMethod').inc(1); - - return indexer.getMethod(blockHash, contractAddress); - }, - - _test: (_: any, { blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise => { - log('_test', blockHash, contractAddress); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('_test').inc(1); - - return indexer._test(blockHash, contractAddress); - }, - - blog: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('blog', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('blog').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(Blog, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - category: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('category', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('category').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(Category, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - author: async ( - _: any, - { id, block = {} }: { id: string, block: BlockHeight }, - __: any, - info: GraphQLResolveInfo - ) => { - log('author', id, JSON.stringify(block, jsonBigIntStringReplacer)); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('author').inc(1); - assert(info.fieldNodes[0].selectionSet); - - // Set cache-control hints - setGQLCacheHints(info, block, gqlCacheConfig); - - return indexer.getSubgraphEntity(Author, id, block, info.fieldNodes[0].selectionSet.selections); - }, - - events: async (_: any, { blockHash, contractAddress, name }: { blockHash: string, contractAddress: string, name?: string }) => { - log('events', blockHash, contractAddress, name); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('events').inc(1); - - const block = await indexer.getBlockProgress(blockHash); - if (!block || !block.isComplete) { - throw new Error(`Block hash ${blockHash} number ${block?.blockNumber} not processed yet`); - } - - const events = await indexer.getEventsByFilter(blockHash, contractAddress, name); - return events.map(event => indexer.getResultEvent(event)); - }, - - eventsInRange: async (_: any, { fromBlockNumber, toBlockNumber }: { fromBlockNumber: number, toBlockNumber: number }) => { - log('eventsInRange', fromBlockNumber, toBlockNumber); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('eventsInRange').inc(1); - - const { expected, actual } = await indexer.getProcessedBlockCountForRange(fromBlockNumber, toBlockNumber); - if (expected !== actual) { - throw new Error(`Range not available, expected ${expected}, got ${actual} blocks in range`); - } - - const events = await indexer.getEventsInRange(fromBlockNumber, toBlockNumber); - return events.map(event => indexer.getResultEvent(event)); - }, - - getStateByCID: async (_: any, { cid }: { cid: string }) => { - log('getStateByCID', cid); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('getStateByCID').inc(1); - - const state = await indexer.getStateByCID(cid); - - return state && state.block.isComplete ? getResultState(state) : undefined; - }, - - getState: async (_: any, { blockHash, contractAddress, kind }: { blockHash: string, contractAddress: string, kind: string }) => { - log('getState', blockHash, contractAddress, kind); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('getState').inc(1); - - const state = await indexer.getPrevState(blockHash, contractAddress, kind); - - return state && state.block.isComplete ? getResultState(state) : undefined; - }, - - getSyncStatus: async () => { - log('getSyncStatus'); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('getSyncStatus').inc(1); - - return indexer.getSyncStatus(); - } - } - }; -}; diff --git a/packages/graph-test-watcher/src/schema.gql b/packages/graph-test-watcher/src/schema.gql deleted file mode 100644 index 6cdb1581..00000000 --- a/packages/graph-test-watcher/src/schema.gql +++ /dev/null @@ -1,144 +0,0 @@ -enum CacheControlScope { - PUBLIC - PRIVATE -} - -directive @cacheControl( - maxAge: Int - scope: CacheControlScope - inheritMaxAge: Boolean -) on FIELD_DEFINITION | OBJECT | INTERFACE | UNION - -scalar BigInt - -scalar Bytes - -scalar BigDecimal - -input Block_height { - hash: Bytes - number: Int -} - -type Proof { - data: String! -} - -type ResultBoolean { - value: Boolean! - proof: Proof -} - -type ResultString { - value: String! - proof: Proof -} - -type ResultInt { - value: Int! - proof: Proof -} - -type ResultBigInt { - value: BigInt! - proof: Proof -} - -type Block { - cid: String! - hash: String! - number: Int! - timestamp: Int! - parentHash: String! -} - -type Transaction { - hash: String! - index: Int! - from: String! - to: String! -} - -type ResultEvent { - block: Block! - tx: Transaction! - contract: String! - eventIndex: Int! - event: Event! - proof: Proof -} - -union Event = TestEvent - -type TestEvent { - param1: String! - param2: Int! - param3: BigInt! -} - -type ResultState { - block: Block! - contractAddress: String! - cid: String! - kind: String! - data: String! -} - -type SyncStatus { - latestIndexedBlockHash: String! - latestIndexedBlockNumber: Int! - latestCanonicalBlockHash: String! - latestCanonicalBlockNumber: Int! -} - -type Query { - events(blockHash: String!, contractAddress: String!, name: String): [ResultEvent!] - eventsInRange(fromBlockNumber: Int!, toBlockNumber: Int!): [ResultEvent!] - getMethod(blockHash: String!, contractAddress: String!): ResultString! - _test(blockHash: String!, contractAddress: String!): ResultBigInt! - blog(id: String!, block: Block_height): Blog! - author(id: String!, block: Block_height): Author! - category(id: String!, block: Block_height): Category! - getStateByCID(cid: String!): ResultState - getState(blockHash: String!, contractAddress: String!, kind: String): ResultState - getSyncStatus: SyncStatus -} - -enum BlogKind { - short - long -} - -type Blog { - id: ID! - kind: BlogKind! - isActive: Boolean! - reviews: [BigInt!]! - author: Author! @cacheControl(inheritMaxAge: true) - categories: [Category!]! @cacheControl(inheritMaxAge: true) -} - -type Category { - id: ID! - count: BigInt! - name: String! -} - -type Author { - id: ID! - blogCount: BigInt! - name: String! - rating: BigDecimal! - paramInt: Int! - paramBigInt: BigInt! - paramBytes: Bytes! - blogs: [Blog!]! @cacheControl(inheritMaxAge: true) -} - -type Mutation { - watchContract(address: String!, kind: String!, checkpoint: Boolean!, startingBlock: Int): Boolean! -} - -type Subscription { - onEvent: ResultEvent! -} diff --git a/packages/graph-test-watcher/src/server.ts b/packages/graph-test-watcher/src/server.ts deleted file mode 100644 index d55266d9..00000000 --- a/packages/graph-test-watcher/src/server.ts +++ /dev/null @@ -1,42 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import fs from 'fs'; -import path from 'path'; -import 'reflect-metadata'; -import debug from 'debug'; - -import { ServerCmd } from '@cerc-io/cli'; -import { getGraphDbAndWatcher } from '@cerc-io/graph-node'; - -import { createResolvers } from './resolvers'; -import { Indexer } from './indexer'; -import { Database, ENTITY_QUERY_TYPE_MAP, ENTITY_TO_LATEST_ENTITY_MAP } from './database'; - -const log = debug('vulcanize:server'); - -export const main = async (): Promise => { - const serverCmd = new ServerCmd(); - await serverCmd.init(Database); - - const { graphWatcher } = await getGraphDbAndWatcher( - serverCmd.config.server, - serverCmd.clients.ethClient, - serverCmd.ethProvider, - serverCmd.database.baseDatabase, - ENTITY_QUERY_TYPE_MAP, - ENTITY_TO_LATEST_ENTITY_MAP - ); - - await serverCmd.initIndexer(Indexer, graphWatcher); - - const typeDefs = fs.readFileSync(path.join(__dirname, 'schema.gql')).toString(); - return serverCmd.exec(createResolvers, typeDefs); -}; - -main().then(() => { - log('Starting server...'); -}).catch(err => { - log(err); -}); diff --git a/packages/graph-test-watcher/tsconfig.json b/packages/graph-test-watcher/tsconfig.json deleted file mode 100644 index 4e55bfd1..00000000 --- a/packages/graph-test-watcher/tsconfig.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "compilerOptions": { - /* Visit https://aka.ms/tsconfig.json to read more about this file */ - - /* Basic Options */ - // "incremental": true, /* Enable incremental compilation */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ - "lib": ["es2019"], /* Specify library files to be included in the compilation. */ - // "allowJs": true, /* Allow javascript files to be compiled. */ - // "checkJs": true, /* Report errors in .js files. */ - // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ - // "declaration": true, /* Generates corresponding '.d.ts' file. */ - // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - "sourceMap": true, /* Generates corresponding '.map' file. */ - // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "dist", /* Redirect output structure to the directory. */ - // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - // "composite": true, /* Enable project compilation */ - // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ - // "removeComments": true, /* Do not emit comments to output. */ - // "noEmit": true, /* Do not emit outputs. */ - // "importHelpers": true, /* Import emit helpers from 'tslib'. */ - "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ - // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* Enable strict null checks. */ - // "strictFunctionTypes": true, /* Enable strict checking of function types. */ - // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ - // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ - // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - - /* Additional Checks */ - // "noUnusedLocals": true, /* Report errors on unused locals. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ - - /* Module Resolution Options */ - // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ - // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ - // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ - // "typeRoots": [], /* List of folders to include type definitions from. */ - // "types": [], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ - // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - - /* Source Map Options */ - // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ - // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - - /* Experimental Options */ - "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ - // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - - /* Advanced Options */ - "skipLibCheck": true, /* Skip type checking of declaration files. */ - "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ - "resolveJsonModule": true /* Enabling the option allows importing JSON, and validating the types in that JSON file. */ - }, - "include": ["src/**/*"] -} diff --git a/packages/mobymask-v2-watcher/.eslintignore b/packages/mobymask-v2-watcher/.eslintignore deleted file mode 100644 index 55cb5225..00000000 --- a/packages/mobymask-v2-watcher/.eslintignore +++ /dev/null @@ -1,2 +0,0 @@ -# Don't lint build output. -dist diff --git a/packages/mobymask-v2-watcher/.eslintrc.json b/packages/mobymask-v2-watcher/.eslintrc.json deleted file mode 100644 index a2b842c2..00000000 --- a/packages/mobymask-v2-watcher/.eslintrc.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "env": { - "browser": true, - "es2021": true - }, - "extends": [ - "semistandard", - "plugin:@typescript-eslint/recommended" - ], - "parser": "@typescript-eslint/parser", - "parserOptions": { - "ecmaVersion": 12, - "sourceType": "module" - }, - "plugins": [ - "@typescript-eslint" - ], - "rules": { - "indent": ["error", 2, { "SwitchCase": 1 }], - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/explicit-module-boundary-types": [ - "warn", - { - "allowArgumentsExplicitlyTypedAsAny": true - } - ] - } -} diff --git a/packages/mobymask-v2-watcher/README.md b/packages/mobymask-v2-watcher/README.md deleted file mode 100644 index 134195e6..00000000 --- a/packages/mobymask-v2-watcher/README.md +++ /dev/null @@ -1,281 +0,0 @@ -# MobyMask v2 Watcher - -First try the [mobymask demo in stack orchestrator](https://github.com/cerc-io/stack-orchestrator/tree/main/app/data/stacks/mobymask) to quickly get started. Advanced users can see [here](/docs/README.md) for instructions on setting up a local environment by hand. - -## Setup - -Run the following command to install required packages: - -```bash -yarn && yarn build -``` - -If the watcher is "lazy", run the server: - -```bash -yarn server -``` - -GQL console: http://localhost:3010/graphql - -If the watcher is "active", run the job-runner: - -```bash -yarn job-runner -``` -then the server: - -```bash -yarn server -``` - -Next, clone the MobyMask repo and checkout this branch: - -```bash -git clone https://github.com/cerc-io/MobyMask && cd MobyMask -git checkout use-laconic-watcher-as-hosted-index -``` - -Install the packages: -```bash -yarn -``` - -Deploy the contract: -```bash -cd packages/hardhat - -yarn deploy -# deploying "PhisherRegistry" (tx: 0xaebeb2e883ece1f679304ec46f5dc61ca74f9e168427268a7dfa8802195b8de0)...: deployed at 0xMobyAddress with 2306221 gas -# $ hardhat run scripts/publish.js -# ✅ Published contracts to the subgraph package. -# Done in 14.28s. -``` - -Export the address of the deployed contract to a shell variable for later use: - -```bash -export MOBY_ADDRESS="0xMobyAddress" -``` - -Run the following GQL mutation in watcher GraphQL endpoint http://127.0.0.1:3010/graphql - -```graphql -mutation { - watchContract( - address: "MOBY_ADDRESS" - kind: "PhisherRegistry" - checkpoint: true - ) -} -``` - -Get the latest block - - ```graphql - query { - latestBlock { - hash - number - } - } - ``` - -Run the following GQL query in GraphQL endpoint - -```graphql -query { - isPhisher( - blockHash: "LATEST_BLOCK_HASH" - contractAddress: "MOBY_ADDRESS" - key0: "TWT:phishername" - ) { - value - proof { - data - } - } - isMember( - blockHash: "LATEST_BLOCK_HASH" - contractAddress: "MOBY_ADDRESS" - key0: "TWT:membername" - ) { - value - proof { - data - } - } -} -``` - -Run the following GQL subscription in generated watcher GraphQL endpoint: - -```graphql -subscription { - onEvent { - event { - __typename - ... on PhisherStatusUpdatedEvent { - entity - isPhisher - }, - ... on MemberStatusUpdatedEvent { - entity - isMember - } - }, - block { - number - hash - } - } -} -``` - -Update isPhiser and isMember lists with names - -```bash -yarn claimPhisher --contract $MOBY_ADDRESS --name phisherName -``` - -```bash -yarn claimMember --contract $MOBY_ADDRESS --name memberName -``` - -- The events should be visible in the subscription at GQL endpoint. Note down the event blockHash from result. - -- The isMember and isPhisher lists should be indexed. Check the database (mobymask-v2-watcher) tables `is_phisher` and `is_member`, there should be entries at the event blockHash and the value should be true. The data is indexed in `handleEvent` method in the [hooks file](./src/hooks.ts). - -Update the the previous query with event blockHash and check isPhisher and isMember in GraphQL playground - -```graphql -query { - isPhisher( - blockHash: "EVENT_BLOCK_HASH" - contractAddress: "MOBY_ADDRESS", - key0: "TWT:phishername" - ) { - value - proof { - data - } - } - - isMember( - blockHash: "EVENT_BLOCK_HASH" - contractAddress: "MOBY_ADDRESS", - key0: "TWT:membername" - ) { - value - proof { - data - } - } -} -``` - -The data is fetched from watcher database as it is already indexed. - -## Additional Commands - -To watch a contract, run: - -```bash -yarn watch:contract --address --kind --checkpoint --starting-block [block-number] -``` -where: -- `address`: Address or identifier of the contract to be watched. -- `kind`: Kind of the contract. -- `checkpoint`: Turn checkpointing on (`true` | `false`). -- `starting-block`: Starting block for the contract (default: `1`). - -Examples: - -Watch a contract with its address and checkpointing on: - -```bash -yarn watch:contract --address 0x1F78641644feB8b64642e833cE4AFE93DD6e7833 --kind ERC20 --checkpoint true -``` - -Watch a contract with its identifier and checkpointing on: - -```bash -yarn watch:contract --address MyProtocol --kind protocol --checkpoint true -``` - -To fill a block range: - -```bash -yarn fill --start-block --end-block -``` - -* `start-block`: Block number to start filling from. -* `end-block`: Block number till which to fill. - -To create a checkpoint for a contract: - -```bash -yarn checkpoint create --address --block-hash [block-hash] -``` - -* `address`: Address or identifier of the contract for which to create a checkpoint. -* `block-hash`: Hash of a block (in the pruned region) at which to create the checkpoint (default: latest canonical block hash). - -To reset the watcher to a previous block number: - -```bash -yarn reset watcher --block-number -``` - -Reset job-queue: - -```bash -yarn reset job-queue -``` - -Reset state: - -```bash -yarn reset state --block-number -``` - -* `block-number`: Block number to which to reset the watcher. - -To export and import the watcher state: - -In the source watcher, export watcher state: - -```bash -yarn export-state --export-file [export-file-path] --block-number [snapshot-block-height] -``` - -* `export-file`: Path of file to which to export the watcher data. -* `block-number`: Block height at which to take snapshot for export. - -In the target watcher, run job-runner: - -```bash -yarn job-runner -``` - -Import watcher state: - -```bash -yarn import-state --import-file -``` - -* `import-file`: Path of file from which to import the watcher data. - -Run server: - -```bash -yarn server -``` - -To inspect a CID: - -```bash -yarn inspect-cid --cid -``` - -* `cid`: CID to be inspected. diff --git a/packages/mobymask-v2-watcher/environments/local.toml b/packages/mobymask-v2-watcher/environments/local.toml deleted file mode 100644 index 981a57eb..00000000 --- a/packages/mobymask-v2-watcher/environments/local.toml +++ /dev/null @@ -1,76 +0,0 @@ -[server] - host = "127.0.0.1" - port = 3010 - kind = "lazy" - - # Checkpointing state. - checkpointing = true - - # Checkpoint interval in number of blocks. - checkpointInterval = 2000 - - # Enable state creation - enableState = true - - # Boolean to filter logs by contract. - filterLogs = true - - # Max block range for which to return events in eventsInRange GQL query. - # Use -1 for skipping check on block range. - maxEventsBlockRange = -1 - - [server.p2p] - enableRelay = true - enablePeer = true - - [server.p2p.relay] - host = "127.0.0.1" - port = 9090 - relayPeers = [] - peerIdFile = '' - - [server.p2p.peer] - relayMultiaddr = '' - pubSubTopic = 'mobymask' - peerIdFile = '' - enableL2Txs = false - - [server.p2p.peer.l2TxsConfig] - privateKey = '' - contractAddress = '' - -[metrics] - host = "127.0.0.1" - port = 9000 - - [metrics.gql] - port = 9001 - -[database] - type = "postgres" - host = "localhost" - port = 5432 - database = "mobymask-v2-watcher" - username = "postgres" - password = "postgres" - synchronize = true - logging = false - -[upstream] - [upstream.ethServer] - gqlApiEndpoint = "http://127.0.0.1:8082/graphql" - rpcProviderEndpoint = "http://127.0.0.1:8081" - - [upstream.cache] - name = "requests" - enabled = false - deleteOnStart = false - -[jobQueue] - dbConnectionString = "postgres://postgres:postgres@localhost/mobymask-v2-watcher-job-queue" - maxCompletionLagInSecs = 300 - jobDelayInMilliSecs = 100 - eventsInBatch = 50 - blockDelayInMilliSecs = 2000 - prefetchBlocksInMem = true - prefetchBlockCount = 10 diff --git a/packages/mobymask-v2-watcher/indexing.md b/packages/mobymask-v2-watcher/indexing.md deleted file mode 100644 index f93509ba..00000000 --- a/packages/mobymask-v2-watcher/indexing.md +++ /dev/null @@ -1,218 +0,0 @@ -# Index missing blocks with eth-statediff-service - -This readme can be followed to index required blocks out of order for a contract. This indexed data can then be used by the watcher further. - -* For indexing the required blocks the following core services will be used: - - * [ipld-eth-db](https://github.com/vulcanize/ipld-eth-db) - - * Run ipld-eth-db database using docker: - - ```bash - docker-compose -f docker-compose.yml up - ``` - - * [leveldb-ethdb-rpc](https://github.com/vulcanize/leveldb-ethdb-rpc) - - It is an RPC wrapper around LevelDB. The endpoint can be used by eth-statediff-service to access LevelDB. - - * [eth-statediff-service](https://github.com/vulcanize/eth-statediff-service) - - * The [config file](https://github.com/vulcanize/eth-statediff-service/blob/sharding/environments/config.toml) can be updated with the following for running eth-statediff-service: - - ```toml - [leveldb] - mode = "remote" - # leveldb-ethdb-rpc endpoint - url = "http://127.0.0.1:8082/" - - [server] - httpPath = "0.0.0.0:8545" - - [statediff] - prerun = false - serviceWorkers = 2 - workerQueueSize = 1024 - trieWorkers = 16 - - [log] - level = "info" - - [database] - # Credentials for ipld-eth-db database - name = "vulcanize_testing" - hostname = "localhost" - port = 8077 - user = "vdbm" - password = "password" - type = "postgres" - driver = "sqlx" - - [cache] - database = 1024 - trie = 4096 - - [ethereum] - # Config for mainnet - nodeID = "1" - clientName = "eth-statediff-service" - networkID = 1 - chainID = 1 - ``` - - * Run eth-statediff-service: - - ```bash - make build && ./eth-statediff-service serve --config environments/config.toml - ``` - -* Indexing required blocks can be done in the following way: - - * Call `writeStateDiffAt` API with watched addresses for required blocks: - - ```bash - # Replace $BLOCK_NUMBER with required block number to index and $CONTRACT_ADDRESS with the contract of interest. - curl -X POST -H 'Content-Type: application/json' --data '{"jsonrpc":"2.0","method":"statediff_writeStateDiffAt","params":[$BLOCK_NUMBER, {"intermediateStateNodes":true,"intermediateStorageNodes":true,"includeBlock":true,"includeReceipts":true,"includeTD":true,"includeCode":true,"watchedAddresses":["$CONTRACT_ADDRESS"]}],"id":1}' "127.0.0.1":"8545" - ``` - - Example for indexing [mainnet MobyMask blocks](https://etherscan.io/address/0xb06e6db9288324738f04fcaac910f5a60102c1f8): - - 14869713 - - 14875233 - - 14876405 - - 14884873 - - 14885755 - - ```bash - curl -X POST -H 'Content-Type: application/json' --data '{"jsonrpc":"2.0","method":"statediff_writeStateDiffAt","params":[14869713, {"intermediateStateNodes":true,"intermediateStorageNodes":true,"includeBlock":true,"includeReceipts":true,"includeTD":true,"includeCode":true,"watchedAddresses":["0xB06E6DB9288324738f04fCAAc910f5A60102C1F8"]}],"id":1}' "127.0.0.1":"8545" - ``` - - After successfully completing writeStateDiffAt for a block the returned response is: - - ```bash - curl: (52) Empty reply from server - ``` - - **NOTE**: Using remote leveldb-ethdb-rpc takes long time (6-20 minutes). - - * Stop the eth-statediff-service after all required blocks are indexed. - -* Start the [ipld-eth-server](https://github.com/vulcanize/eth-statediff-service) to query the indexed data from watcher. - - * Create the following config.toml file for ipld-eth-server in [environments directory](https://github.com/vulcanize/ipld-eth-server/tree/sharding/environments): - - ```toml - [database] - # Credentials for ipld-eth-db database - name = "vulcanize_testing" # $DATABASE_NAME - hostname = "localhost" # $DATABASE_HOSTNAME - port = 8077 # $DATABASE_PORT - user = "vdbm" # $DATABASE_USER - password = "password" # $DATABASE_PASSWORD - - [log] - level = "info" # $LOGRUS_LEVEL - - [ethereum] - # Config for mainnet - chainID = "1" # $ETH_CHAIN_ID - nodeID = "arch1" # $ETH_NODE_ID - clientName = "Geth" # $ETH_CLIENT_NAME - networkID = "1" # $ETH_NETWORK_ID - ``` - - * Run the server with the config above: - - ```bash - make build && ./ipld-eth-server serve --config=./environments/config.toml --eth-server-graphql --log-level info - ``` - -* The following steps are for indexing blocks out of order in the watcher: - - * Follow [steps in the readme](./README.md#setup) to setup the watcher. - - * Watch the contract: - - ```bash - # Replace $CONTRACT_ADDRESS and $CONTRACT_NAME witch actual values - yarn watch:contract --address $CONTRACT_ADDRESS --kind $CONTRACT_NAME --checkpoint true - - # Example for mobymask-v2-watcher - yarn watch:contract --address 0xB06E6DB9288324738f04fCAAc910f5A60102C1F8 --kind PhisherRegistry --checkpoint true - ``` - - * Index the required blocks. They should be the same blocks indexed by eth-statediff-service above. - - ```bash - # Replace $BLOCK_NUMBER with required block number to index - yarn index-block --block $BLOCK_NUMBER - ``` - - Example for [mainnet MobyMask blocks](https://etherscan.io/address/0xb06e6db9288324738f04fcaac910f5a60102c1f8) indexed above: - ```bash - yarn index-block --block 14869713 - ``` - - * Check the `event` and `block_progress` table to confirm that the required blocks have been indexed properly. - -* The watcher can be started to perform queries on the indexed data: - - * The watcher can be started in lazy mode: - - * Update `server.kind` in [config](./environments/local.toml): - - ```toml - [server] - kind = "lazy" - ``` - - * Run server: - - ```bash - yarn server - ``` - - * Run query in [GraphQL endpoint](http://127.0.0.1:3010/graphql) to get events in a range. Following query is for getting events in the range of mainnet blocks indexed for mobymask-v2-watcher: - - ```graphql - query { - eventsInRange( - # Range for mainnet data blocks - fromBlockNumber: 14869713 - toBlockNumber: 14885755 - ) { - block { - hash - number - } - tx { - hash - } - contract - eventIndex - event { - __typename - } - proof { - data - } - } - } - ``` - - * Run query to get contract storage variable values. The following query is for getting value of `isMember` variable in MobyMask contract: - - ```graphql - query { - isMember( - # BlockHash of an indexed mainnet block that can be taken from the events returned above - blockHash: "0x28cb16e740cd5d7de869bee2957e7442790e9d774e6e71804a67933c7e628038" - contractAddress: "0xB06E6DB9288324738f04fCAAc910f5A60102C1F8" - key0: "TWT:danfinlay" - ) { - value - proof { - data - } - } - } - ``` diff --git a/packages/mobymask-v2-watcher/package.json b/packages/mobymask-v2-watcher/package.json deleted file mode 100644 index ecf8d3fc..00000000 --- a/packages/mobymask-v2-watcher/package.json +++ /dev/null @@ -1,73 +0,0 @@ -{ - "name": "@cerc-io/mobymask-v2-watcher", - "version": "0.2.38", - "description": "mobymask-v2-watcher", - "private": true, - "main": "dist/index.js", - "scripts": { - "lint": "eslint .", - "build": "yarn clean && tsc && yarn copy-assets", - "clean": "rm -rf ./dist", - "copy-assets": "copyfiles -u 1 src/**/*.gql dist/", - "server": "DEBUG='vulcanize:*, laconic:*' YARN_CHILD_PROCESS=true node --enable-source-maps dist/server.js", - "server:dev": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true ts-node src/server.ts", - "job-runner": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true node --enable-source-maps dist/job-runner.js", - "job-runner:dev": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true ts-node src/job-runner.ts", - "watch:contract": "DEBUG=vulcanize:* ts-node src/cli/watch-contract.ts", - "fill": "DEBUG=vulcanize:* ts-node src/fill.ts", - "reset": "DEBUG=vulcanize:* ts-node src/cli/reset.ts", - "checkpoint": "DEBUG=vulcanize:* node --enable-source-maps dist/cli/checkpoint.js", - "checkpoint:dev": "DEBUG=vulcanize:* ts-node src/cli/checkpoint.ts", - "export-state": "DEBUG=vulcanize:* node --enable-source-maps dist/cli/export-state.js", - "export-state:dev": "DEBUG=vulcanize:* ts-node src/cli/export-state.ts", - "import-state": "DEBUG=vulcanize:* node --enable-source-maps dist/cli/import-state.js", - "import-state:dev": "DEBUG=vulcanize:* ts-node src/cli/import-state.ts", - "inspect-cid": "DEBUG=vulcanize:* ts-node src/cli/inspect-cid.ts", - "index-block": "DEBUG=vulcanize:* ts-node src/cli/index-block.ts", - "peer": "DEBUG='vulcanize:*, laconic:*' node --enable-source-maps dist/cli/peer.js" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/cerc-io/watcher-ts.git" - }, - "author": "", - "license": "AGPL-3.0", - "bugs": { - "url": "https://github.com/cerc-io/watcher-ts/issues" - }, - "homepage": "https://github.com/cerc-io/watcher-ts#readme", - "dependencies": { - "@apollo/client": "^3.3.19", - "@cerc-io/cli": "^0.2.38", - "@cerc-io/ipld-eth-client": "^0.2.38", - "@cerc-io/peer": "^0.2.38", - "@cerc-io/solidity-mapper": "^0.2.38", - "@cerc-io/util": "^0.2.38", - "@ethersproject/providers": "^5.4.4", - "apollo-type-bigint": "^0.1.3", - "debug": "^4.3.1", - "decimal.js": "^10.3.1", - "ethers": "^5.4.4", - "graphql": "^15.5.0", - "json-bigint": "^1.0.0", - "reflect-metadata": "^0.1.13", - "typeorm": "^0.2.32", - "yargs": "^17.0.1" - }, - "devDependencies": { - "@ethersproject/abi": "^5.3.0", - "@types/yargs": "^17.0.0", - "@typescript-eslint/eslint-plugin": "^5.47.1", - "@typescript-eslint/parser": "^5.47.1", - "copyfiles": "^2.4.1", - "eslint": "^8.35.0", - "eslint-config-semistandard": "^15.0.1", - "eslint-config-standard": "^16.0.3", - "eslint-plugin-import": "^2.27.5", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-promise": "^5.1.0", - "eslint-plugin-standard": "^5.0.0", - "ts-node": "^10.2.1", - "typescript": "^5.0.2" - } -} diff --git a/packages/mobymask-v2-watcher/src/artifacts/PhisherRegistry.json b/packages/mobymask-v2-watcher/src/artifacts/PhisherRegistry.json deleted file mode 100644 index 71bf3d46..00000000 --- a/packages/mobymask-v2-watcher/src/artifacts/PhisherRegistry.json +++ /dev/null @@ -1,1934 +0,0 @@ -{ - "abi": [ - { - "inputs": [ - { - "internalType": "string", - "name": "name", - "type": "string" - } - ], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "address", - "name": "principal", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "agent", - "type": "address" - } - ], - "name": "DelegationTriggered", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "string", - "name": "entity", - "type": "string" - }, - { - "indexed": false, - "internalType": "bool", - "name": "isMember", - "type": "bool" - } - ], - "name": "MemberStatusUpdated", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "previousOwner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "newOwner", - "type": "address" - } - ], - "name": "OwnershipTransferred", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "string", - "name": "entity", - "type": "string" - }, - { - "indexed": false, - "internalType": "bool", - "name": "isPhisher", - "type": "bool" - } - ], - "name": "PhisherStatusUpdated", - "type": "event" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "_input", - "type": "tuple[]" - } - ], - "name": "GET_CAVEAT_ARRAY_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_CAVEAT_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_DELEGATION_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "string", - "name": "name", - "type": "string" - }, - { - "internalType": "string", - "name": "version", - "type": "string" - }, - { - "internalType": "uint256", - "name": "chainId", - "type": "uint256" - }, - { - "internalType": "address", - "name": "verifyingContract", - "type": "address" - } - ], - "internalType": "struct EIP712Domain", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_EIP712DOMAIN_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "bytes32", - "name": "delegationHash", - "type": "bytes32" - } - ], - "internalType": "struct IntentionToRevoke", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_INTENTIONTOREVOKE_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "authority", - "type": "tuple[]" - } - ], - "internalType": "struct Invocation[]", - "name": "batch", - "type": "tuple[]" - }, - { - "components": [ - { - "internalType": "uint256", - "name": "nonce", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "queue", - "type": "uint256" - } - ], - "internalType": "struct ReplayProtection", - "name": "replayProtection", - "type": "tuple" - } - ], - "internalType": "struct Invocations", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_INVOCATIONS_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "authority", - "type": "tuple[]" - } - ], - "internalType": "struct Invocation[]", - "name": "_input", - "type": "tuple[]" - } - ], - "name": "GET_INVOCATION_ARRAY_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "authority", - "type": "tuple[]" - } - ], - "internalType": "struct Invocation", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_INVOCATION_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "nonce", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "queue", - "type": "uint256" - } - ], - "internalType": "struct ReplayProtection", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_REPLAYPROTECTION_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "_input", - "type": "tuple[]" - } - ], - "name": "GET_SIGNEDDELEGATION_ARRAY_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_SIGNEDDELEGATION_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - }, - { - "components": [ - { - "internalType": "bytes32", - "name": "delegationHash", - "type": "bytes32" - } - ], - "internalType": "struct IntentionToRevoke", - "name": "intentionToRevoke", - "type": "tuple" - } - ], - "internalType": "struct SignedIntentionToRevoke", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_SIGNEDINTENTIONTOREVOKE_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "authority", - "type": "tuple[]" - } - ], - "internalType": "struct Invocation[]", - "name": "batch", - "type": "tuple[]" - }, - { - "components": [ - { - "internalType": "uint256", - "name": "nonce", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "queue", - "type": "uint256" - } - ], - "internalType": "struct ReplayProtection", - "name": "replayProtection", - "type": "tuple" - } - ], - "internalType": "struct Invocations", - "name": "invocations", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedInvocation", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_SIGNEDINVOCATION_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_TRANSACTION_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "string", - "name": "identifier", - "type": "string" - }, - { - "internalType": "bool", - "name": "isNominated", - "type": "bool" - } - ], - "name": "claimIfMember", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "string", - "name": "identifier", - "type": "string" - }, - { - "internalType": "bool", - "name": "isAccused", - "type": "bool" - } - ], - "name": "claimIfPhisher", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "authority", - "type": "tuple[]" - } - ], - "internalType": "struct Invocation[]", - "name": "batch", - "type": "tuple[]" - } - ], - "name": "contractInvoke", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "domainHash", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - }, - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "internalType": "bytes32", - "name": "delegationHash", - "type": "bytes32" - } - ], - "name": "enforceCaveat", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - } - ], - "name": "getDelegationTypedDataHash", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "string", - "name": "contractName", - "type": "string" - }, - { - "internalType": "string", - "name": "version", - "type": "string" - }, - { - "internalType": "uint256", - "name": "chainId", - "type": "uint256" - }, - { - "internalType": "address", - "name": "verifyingContract", - "type": "address" - } - ], - "name": "getEIP712DomainHash", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "bytes32", - "name": "delegationHash", - "type": "bytes32" - } - ], - "internalType": "struct IntentionToRevoke", - "name": "intentionToRevoke", - "type": "tuple" - } - ], - "name": "getIntentionToRevokeTypedDataHash", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "authority", - "type": "tuple[]" - } - ], - "internalType": "struct Invocation[]", - "name": "batch", - "type": "tuple[]" - }, - { - "components": [ - { - "internalType": "uint256", - "name": "nonce", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "queue", - "type": "uint256" - } - ], - "internalType": "struct ReplayProtection", - "name": "replayProtection", - "type": "tuple" - } - ], - "internalType": "struct Invocations", - "name": "invocations", - "type": "tuple" - } - ], - "name": "getInvocationsTypedDataHash", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "authority", - "type": "tuple[]" - } - ], - "internalType": "struct Invocation[]", - "name": "batch", - "type": "tuple[]" - }, - { - "components": [ - { - "internalType": "uint256", - "name": "nonce", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "queue", - "type": "uint256" - } - ], - "internalType": "struct ReplayProtection", - "name": "replayProtection", - "type": "tuple" - } - ], - "internalType": "struct Invocations", - "name": "invocations", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedInvocation[]", - "name": "signedInvocations", - "type": "tuple[]" - } - ], - "name": "invoke", - "outputs": [ - { - "internalType": "bool", - "name": "success", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "name": "isMember", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "name": "isPhisher", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - }, - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "name": "multiNonce", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "owner", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "renounceOwnership", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation", - "name": "signedDelegation", - "type": "tuple" - }, - { - "components": [ - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - }, - { - "components": [ - { - "internalType": "bytes32", - "name": "delegationHash", - "type": "bytes32" - } - ], - "internalType": "struct IntentionToRevoke", - "name": "intentionToRevoke", - "type": "tuple" - } - ], - "internalType": "struct SignedIntentionToRevoke", - "name": "signedIntentionToRevoke", - "type": "tuple" - } - ], - "name": "revokeDelegation", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "newOwner", - "type": "address" - } - ], - "name": "transferOwnership", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation", - "name": "signedDelegation", - "type": "tuple" - } - ], - "name": "verifyDelegationSignature", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - }, - { - "components": [ - { - "internalType": "bytes32", - "name": "delegationHash", - "type": "bytes32" - } - ], - "internalType": "struct IntentionToRevoke", - "name": "intentionToRevoke", - "type": "tuple" - } - ], - "internalType": "struct SignedIntentionToRevoke", - "name": "signedIntentionToRevoke", - "type": "tuple" - } - ], - "name": "verifyIntentionToRevokeSignature", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "authority", - "type": "tuple[]" - } - ], - "internalType": "struct Invocation[]", - "name": "batch", - "type": "tuple[]" - }, - { - "components": [ - { - "internalType": "uint256", - "name": "nonce", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "queue", - "type": "uint256" - } - ], - "internalType": "struct ReplayProtection", - "name": "replayProtection", - "type": "tuple" - } - ], - "internalType": "struct Invocations", - "name": "invocations", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedInvocation", - "name": "signedInvocation", - "type": "tuple" - } - ], - "name": "verifyInvocationSignature", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - } - ], - "storageLayout": { - "storage": [ - { - "astId": 1238, - "contract": "PhisherRegistry.sol:PhisherRegistry", - "label": "_owner", - "offset": 0, - "slot": "0", - "type": "t_address" - }, - { - "astId": 969, - "contract": "PhisherRegistry.sol:PhisherRegistry", - "label": "multiNonce", - "offset": 0, - "slot": "1", - "type": "t_mapping(t_address,t_mapping(t_uint256,t_uint256))" - }, - { - "astId": 1354, - "contract": "PhisherRegistry.sol:PhisherRegistry", - "label": "isRevoked", - "offset": 0, - "slot": "2", - "type": "t_mapping(t_bytes32,t_bool)" - }, - { - "astId": 1554, - "contract": "PhisherRegistry.sol:PhisherRegistry", - "label": "isPhisher", - "offset": 0, - "slot": "3", - "type": "t_mapping(t_string_memory_ptr,t_bool)" - }, - { - "astId": 1585, - "contract": "PhisherRegistry.sol:PhisherRegistry", - "label": "isMember", - "offset": 0, - "slot": "4", - "type": "t_mapping(t_string_memory_ptr,t_bool)" - } - ], - "types": { - "t_address": { - "encoding": "inplace", - "label": "address", - "numberOfBytes": "20" - }, - "t_bool": { - "encoding": "inplace", - "label": "bool", - "numberOfBytes": "1" - }, - "t_bytes32": { - "encoding": "inplace", - "label": "bytes32", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_mapping(t_uint256,t_uint256))": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => mapping(uint256 => uint256))", - "numberOfBytes": "32", - "value": "t_mapping(t_uint256,t_uint256)" - }, - "t_mapping(t_bytes32,t_bool)": { - "encoding": "mapping", - "key": "t_bytes32", - "label": "mapping(bytes32 => bool)", - "numberOfBytes": "32", - "value": "t_bool" - }, - "t_mapping(t_string_memory_ptr,t_bool)": { - "encoding": "mapping", - "key": "t_string_memory_ptr", - "label": "mapping(string => bool)", - "numberOfBytes": "32", - "value": "t_bool" - }, - "t_mapping(t_uint256,t_uint256)": { - "encoding": "mapping", - "key": "t_uint256", - "label": "mapping(uint256 => uint256)", - "numberOfBytes": "32", - "value": "t_uint256" - }, - "t_string_memory_ptr": { - "encoding": "bytes", - "label": "string", - "numberOfBytes": "32" - }, - "t_uint256": { - "encoding": "inplace", - "label": "uint256", - "numberOfBytes": "32" - } - } - } -} \ No newline at end of file diff --git a/packages/mobymask-v2-watcher/src/cli/checkpoint-cmds/create.ts b/packages/mobymask-v2-watcher/src/cli/checkpoint-cmds/create.ts deleted file mode 100644 index 798eeb37..00000000 --- a/packages/mobymask-v2-watcher/src/cli/checkpoint-cmds/create.ts +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import { CreateCheckpointCmd } from '@cerc-io/cli'; - -import { Database } from '../../database'; -import { Indexer } from '../../indexer'; - -export const command = 'create'; - -export const desc = 'Create checkpoint'; - -export const builder = { - address: { - type: 'string', - require: true, - demandOption: true, - describe: 'Contract address to create the checkpoint for.' - }, - blockHash: { - type: 'string', - describe: 'Blockhash at which to create the checkpoint.' - } -}; - -export const handler = async (argv: any): Promise => { - const createCheckpointCmd = new CreateCheckpointCmd(); - await createCheckpointCmd.init(argv, Database); - await createCheckpointCmd.initIndexer(Indexer); - - await createCheckpointCmd.exec(); -}; diff --git a/packages/mobymask-v2-watcher/src/cli/checkpoint.ts b/packages/mobymask-v2-watcher/src/cli/checkpoint.ts deleted file mode 100644 index 6b6c4f64..00000000 --- a/packages/mobymask-v2-watcher/src/cli/checkpoint.ts +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import yargs from 'yargs'; -import 'reflect-metadata'; -import debug from 'debug'; - -import { DEFAULT_CONFIG_PATH } from '@cerc-io/util'; - -import { hideBin } from 'yargs/helpers'; - -const log = debug('vulcanize:checkpoint'); - -const main = async () => { - return yargs(hideBin(process.argv)) - .parserConfiguration({ - 'parse-numbers': false - }).options({ - configFile: { - alias: 'f', - type: 'string', - require: true, - demandOption: true, - describe: 'configuration file path (toml)', - default: DEFAULT_CONFIG_PATH - } - }) - .commandDir('checkpoint-cmds', { extensions: ['ts', 'js'], exclude: /([a-zA-Z0-9\s_\\.\-:])+(.d.ts)$/ }) - .demandCommand(1) - .help() - .argv; -}; - -main().then(() => { - process.exit(); -}).catch(err => { - log(err); -}); diff --git a/packages/mobymask-v2-watcher/src/cli/export-state.ts b/packages/mobymask-v2-watcher/src/cli/export-state.ts deleted file mode 100644 index 998a3365..00000000 --- a/packages/mobymask-v2-watcher/src/cli/export-state.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { ExportStateCmd } from '@cerc-io/cli'; - -import { Database } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:export-state'); - -const main = async (): Promise => { - const exportStateCmd = new ExportStateCmd(); - await exportStateCmd.init(Database); - await exportStateCmd.initIndexer(Indexer); - - await exportStateCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/mobymask-v2-watcher/src/cli/import-state.ts b/packages/mobymask-v2-watcher/src/cli/import-state.ts deleted file mode 100644 index 4560e4bd..00000000 --- a/packages/mobymask-v2-watcher/src/cli/import-state.ts +++ /dev/null @@ -1,28 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { ImportStateCmd } from '@cerc-io/cli'; - -import { Database } from '../database'; -import { Indexer } from '../indexer'; -import { State } from '../entity/State'; - -const log = debug('vulcanize:import-state'); - -export const main = async (): Promise => { - const importStateCmd = new ImportStateCmd(); - await importStateCmd.init(Database); - await importStateCmd.initIndexer(Indexer); - - await importStateCmd.exec(State); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/mobymask-v2-watcher/src/cli/index-block.ts b/packages/mobymask-v2-watcher/src/cli/index-block.ts deleted file mode 100644 index 9969217e..00000000 --- a/packages/mobymask-v2-watcher/src/cli/index-block.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { IndexBlockCmd } from '@cerc-io/cli'; - -import { Database } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:index-block'); - -const main = async (): Promise => { - const indexBlockCmd = new IndexBlockCmd(); - await indexBlockCmd.init(Database); - await indexBlockCmd.initIndexer(Indexer); - - await indexBlockCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/mobymask-v2-watcher/src/cli/inspect-cid.ts b/packages/mobymask-v2-watcher/src/cli/inspect-cid.ts deleted file mode 100644 index 44b694f1..00000000 --- a/packages/mobymask-v2-watcher/src/cli/inspect-cid.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { InspectCIDCmd } from '@cerc-io/cli'; - -import { Database } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:inspect-cid'); - -const main = async (): Promise => { - const inspectCIDCmd = new InspectCIDCmd(); - await inspectCIDCmd.init(Database); - await inspectCIDCmd.initIndexer(Indexer); - - await inspectCIDCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/mobymask-v2-watcher/src/cli/peer.ts b/packages/mobymask-v2-watcher/src/cli/peer.ts deleted file mode 100644 index 9bf45dac..00000000 --- a/packages/mobymask-v2-watcher/src/cli/peer.ts +++ /dev/null @@ -1,20 +0,0 @@ -import debug from 'debug'; - -import { PeerCmd } from '@cerc-io/cli'; - -import { parseLibp2pMessage } from '../libp2p-utils'; - -const log = debug('vulcanize:peer'); - -const MOBYMASK_TOPIC = 'mobymask'; - -export const main = async (): Promise => { - const peerCmd = new PeerCmd(); - await peerCmd.exec(MOBYMASK_TOPIC, parseLibp2pMessage); -}; - -main().then(() => { - log('Starting peer...'); -}).catch(err => { - log(err); -}); diff --git a/packages/mobymask-v2-watcher/src/cli/reset-cmds/job-queue.ts b/packages/mobymask-v2-watcher/src/cli/reset-cmds/job-queue.ts deleted file mode 100644 index a78453c0..00000000 --- a/packages/mobymask-v2-watcher/src/cli/reset-cmds/job-queue.ts +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import debug from 'debug'; - -import { getConfig, resetJobs, Config } from '@cerc-io/util'; - -const log = debug('vulcanize:reset-job-queue'); - -export const command = 'job-queue'; - -export const desc = 'Reset job queue'; - -export const builder = {}; - -export const handler = async (argv: any): Promise => { - const config: Config = await getConfig(argv.configFile); - await resetJobs(config); - - log('Job queue reset successfully'); -}; diff --git a/packages/mobymask-v2-watcher/src/cli/reset-cmds/state.ts b/packages/mobymask-v2-watcher/src/cli/reset-cmds/state.ts deleted file mode 100644 index 9bc0eb76..00000000 --- a/packages/mobymask-v2-watcher/src/cli/reset-cmds/state.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import { ResetStateCmd } from '@cerc-io/cli'; - -import { Database } from '../../database'; - -export const command = 'state'; - -export const desc = 'Reset State to a given block number'; - -export const builder = { - blockNumber: { - type: 'number' - } -}; - -export const handler = async (argv: any): Promise => { - const resetStateCmd = new ResetStateCmd(); - await resetStateCmd.init(argv, Database); - - await resetStateCmd.exec(); -}; diff --git a/packages/mobymask-v2-watcher/src/cli/reset-cmds/watcher.ts b/packages/mobymask-v2-watcher/src/cli/reset-cmds/watcher.ts deleted file mode 100644 index 4201267c..00000000 --- a/packages/mobymask-v2-watcher/src/cli/reset-cmds/watcher.ts +++ /dev/null @@ -1,26 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import { ResetWatcherCmd } from '@cerc-io/cli'; - -import { Database } from '../../database'; -import { Indexer } from '../../indexer'; - -export const command = 'watcher'; - -export const desc = 'Reset watcher to a block number'; - -export const builder = { - blockNumber: { - type: 'number' - } -}; - -export const handler = async (argv: any): Promise => { - const resetWatcherCmd = new ResetWatcherCmd(); - await resetWatcherCmd.init(argv, Database); - await resetWatcherCmd.initIndexer(Indexer); - - await resetWatcherCmd.exec(); -}; diff --git a/packages/mobymask-v2-watcher/src/cli/reset.ts b/packages/mobymask-v2-watcher/src/cli/reset.ts deleted file mode 100644 index b8df3f2f..00000000 --- a/packages/mobymask-v2-watcher/src/cli/reset.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { getResetYargs } from '@cerc-io/util'; - -const log = debug('vulcanize:reset'); - -const main = async () => { - return getResetYargs() - .commandDir('reset-cmds', { extensions: ['ts', 'js'], exclude: /([a-zA-Z0-9\s_\\.\-:])+(.d.ts)$/ }) - .demandCommand(1) - .help() - .argv; -}; - -main().then(() => { - process.exit(); -}).catch(err => { - log(err); -}); diff --git a/packages/mobymask-v2-watcher/src/cli/watch-contract.ts b/packages/mobymask-v2-watcher/src/cli/watch-contract.ts deleted file mode 100644 index 84741a60..00000000 --- a/packages/mobymask-v2-watcher/src/cli/watch-contract.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { WatchContractCmd } from '@cerc-io/cli'; - -import { Database } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:watch-contract'); - -const main = async (): Promise => { - const watchContractCmd = new WatchContractCmd(); - await watchContractCmd.init(Database); - await watchContractCmd.initIndexer(Indexer); - - await watchContractCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/mobymask-v2-watcher/src/client.ts b/packages/mobymask-v2-watcher/src/client.ts deleted file mode 100644 index 99245b84..00000000 --- a/packages/mobymask-v2-watcher/src/client.ts +++ /dev/null @@ -1,100 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import { gql } from '@apollo/client/core'; -import { GraphQLClient, GraphQLConfig } from '@cerc-io/ipld-eth-client'; - -import { queries, mutations, subscriptions } from './gql'; - -export class Client { - _config: GraphQLConfig; - _client: GraphQLClient; - - constructor (config: GraphQLConfig) { - this._config = config; - - this._client = new GraphQLClient(config); - } - - async getMultiNonce (blockHash: string, contractAddress: string, key0: string, key1: bigint): Promise { - const { multiNonce } = await this._client.query( - gql(queries.multiNonce), - { blockHash, contractAddress, key0, key1 } - ); - - return multiNonce; - } - - async _getOwner (blockHash: string, contractAddress: string): Promise { - const { _owner } = await this._client.query( - gql(queries._owner), - { blockHash, contractAddress } - ); - - return _owner; - } - - async getIsRevoked (blockHash: string, contractAddress: string, key0: string): Promise { - const { isRevoked } = await this._client.query( - gql(queries.isRevoked), - { blockHash, contractAddress, key0 } - ); - - return isRevoked; - } - - async getIsPhisher (blockHash: string, contractAddress: string, key0: string): Promise { - const { isPhisher } = await this._client.query( - gql(queries.isPhisher), - { blockHash, contractAddress, key0 } - ); - - return isPhisher; - } - - async getIsMember (blockHash: string, contractAddress: string, key0: string): Promise { - const { isMember } = await this._client.query( - gql(queries.isMember), - { blockHash, contractAddress, key0 } - ); - - return isMember; - } - - async getEvents (blockHash: string, contractAddress: string, name: string): Promise { - const { events } = await this._client.query( - gql(queries.events), - { blockHash, contractAddress, name } - ); - - return events; - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise { - const { eventsInRange } = await this._client.query( - gql(queries.eventsInRange), - { fromBlockNumber, toBlockNumber } - ); - - return eventsInRange; - } - - async watchContract (contractAddress: string, startingBlock?: number): Promise { - const { watchContract } = await this._client.mutate( - gql(mutations.watchContract), - { contractAddress, startingBlock } - ); - - return watchContract; - } - - async watchEvents (onNext: (value: any) => void): Promise { - return this._client.subscribe( - gql(subscriptions.onEvent), - ({ data }) => { - onNext(data.onEvent); - } - ); - } -} diff --git a/packages/mobymask-v2-watcher/src/database.ts b/packages/mobymask-v2-watcher/src/database.ts deleted file mode 100644 index dc36d043..00000000 --- a/packages/mobymask-v2-watcher/src/database.ts +++ /dev/null @@ -1,352 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import assert from 'assert'; -import { Connection, ConnectionOptions, DeepPartial, FindConditions, QueryRunner, FindManyOptions, LessThanOrEqual, EntityTarget } from 'typeorm'; -import path from 'path'; - -import { Database as BaseDatabase, DatabaseInterface, QueryOptions, StateKind, Where } from '@cerc-io/util'; - -import { Contract } from './entity/Contract'; -import { Event } from './entity/Event'; -import { SyncStatus } from './entity/SyncStatus'; -import { StateSyncStatus } from './entity/StateSyncStatus'; -import { BlockProgress } from './entity/BlockProgress'; -import { State } from './entity/State'; -import { MultiNonce } from './entity/MultiNonce'; -import { _Owner } from './entity/_Owner'; -import { IsRevoked } from './entity/IsRevoked'; -import { IsPhisher } from './entity/IsPhisher'; -import { IsMember } from './entity/IsMember'; - -export const ENTITIES = [_Owner, IsMember, IsPhisher, IsRevoked, MultiNonce]; - -export class Database implements DatabaseInterface { - _config: ConnectionOptions; - _conn!: Connection; - _baseDatabase: BaseDatabase; - _propColMaps: { [key: string]: Map; }; - - constructor (config: ConnectionOptions) { - assert(config); - - this._config = { - ...config, - entities: [path.join(__dirname, 'entity/*')] - }; - - this._baseDatabase = new BaseDatabase(this._config); - this._propColMaps = {}; - } - - get baseDatabase (): BaseDatabase { - return this._baseDatabase; - } - - async init (): Promise { - this._conn = await this._baseDatabase.init(); - this._setPropColMaps(); - } - - async close (): Promise { - return this._baseDatabase.close(); - } - - async getMultiNonce ({ blockHash, contractAddress, key0, key1 }: { blockHash: string, contractAddress: string, key0: string, key1: bigint }): Promise { - return this._conn.getRepository(MultiNonce) - .findOne({ - blockHash, - contractAddress, - key0, - key1 - }); - } - - async _getOwner ({ blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise<_Owner | undefined> { - return this._conn.getRepository(_Owner) - .findOne({ - blockHash, - contractAddress - }); - } - - async getIsRevoked ({ blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: string }): Promise { - return this._conn.getRepository(IsRevoked) - .findOne({ - blockHash, - contractAddress, - key0 - }); - } - - async getIsPhisher ({ blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: string }): Promise { - return this._conn.getRepository(IsPhisher) - .findOne({ - blockHash, - contractAddress, - key0 - }); - } - - async getIsMember ({ blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: string }): Promise { - return this._conn.getRepository(IsMember) - .findOne({ - blockHash, - contractAddress, - key0 - }); - } - - async getPrevEntity (entity: new () => Entity, fields: { blockNumber: number } & DeepPartial): Promise { - return this._conn.getRepository(entity) - .findOne({ - where: { - ...fields, - blockNumber: LessThanOrEqual(fields.blockNumber) - } - }); - } - - async saveMultiNonce ({ blockHash, blockNumber, contractAddress, key0, key1, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(MultiNonce); - const entity = repo.create({ blockHash, blockNumber, contractAddress, key0, key1, value, proof }); - return repo.save(entity); - } - - async _saveOwner ({ blockHash, blockNumber, contractAddress, value, proof }: DeepPartial<_Owner>): Promise<_Owner> { - const repo = this._conn.getRepository(_Owner); - const entity = repo.create({ blockHash, blockNumber, contractAddress, value, proof }); - return repo.save(entity); - } - - async saveIsRevoked ({ blockHash, blockNumber, contractAddress, key0, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(IsRevoked); - const entity = repo.create({ blockHash, blockNumber, contractAddress, key0, value, proof }); - return repo.save(entity); - } - - async saveIsPhisher ({ blockHash, blockNumber, contractAddress, key0, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(IsPhisher); - const entity = repo.create({ blockHash, blockNumber, contractAddress, key0, value, proof }); - return repo.save(entity); - } - - async saveIsMember ({ blockHash, blockNumber, contractAddress, key0, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(IsMember); - const entity = repo.create({ blockHash, blockNumber, contractAddress, key0, value, proof }); - return repo.save(entity); - } - - getNewState (): State { - return new State(); - } - - async getStates (where: FindConditions): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getStates(repo, where); - } - - async getLatestState (contractAddress: string, kind: StateKind | null, blockNumber?: number): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getLatestState(repo, contractAddress, kind, blockNumber); - } - - async getPrevState (blockHash: string, contractAddress: string, kind?: string): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getPrevState(repo, blockHash, contractAddress, kind); - } - - // Fetch all diff States after the specified block number. - async getDiffStatesInRange (contractAddress: string, startblock: number, endBlock: number): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getDiffStatesInRange(repo, contractAddress, startblock, endBlock); - } - - async saveOrUpdateState (dbTx: QueryRunner, state: State): Promise { - const repo = dbTx.manager.getRepository(State); - - return this._baseDatabase.saveOrUpdateState(repo, state); - } - - async removeStates (dbTx: QueryRunner, blockNumber: number, kind: string): Promise { - const repo = dbTx.manager.getRepository(State); - - await this._baseDatabase.removeStates(repo, blockNumber, kind); - } - - async removeStatesAfterBlock (dbTx: QueryRunner, blockNumber: number): Promise { - const repo = dbTx.manager.getRepository(State); - - await this._baseDatabase.removeStatesAfterBlock(repo, blockNumber); - } - - async getStateSyncStatus (): Promise { - const repo = this._conn.getRepository(StateSyncStatus); - - return this._baseDatabase.getStateSyncStatus(repo); - } - - async updateStateSyncStatusIndexedBlock (queryRunner: QueryRunner, blockNumber: number, force?: boolean): Promise { - const repo = queryRunner.manager.getRepository(StateSyncStatus); - - return this._baseDatabase.updateStateSyncStatusIndexedBlock(repo, blockNumber, force); - } - - async updateStateSyncStatusCheckpointBlock (queryRunner: QueryRunner, blockNumber: number, force?: boolean): Promise { - const repo = queryRunner.manager.getRepository(StateSyncStatus); - - return this._baseDatabase.updateStateSyncStatusCheckpointBlock(repo, blockNumber, force); - } - - async getContracts (): Promise { - const repo = this._conn.getRepository(Contract); - - return this._baseDatabase.getContracts(repo); - } - - async createTransactionRunner (): Promise { - return this._baseDatabase.createTransactionRunner(); - } - - async getProcessedBlockCountForRange (fromBlockNumber: number, toBlockNumber: number): Promise<{ expected: number, actual: number }> { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getProcessedBlockCountForRange(repo, fromBlockNumber, toBlockNumber); - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise> { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getEventsInRange(repo, fromBlockNumber, toBlockNumber); - } - - async saveEventEntity (queryRunner: QueryRunner, entity: Event): Promise { - const repo = queryRunner.manager.getRepository(Event); - return this._baseDatabase.saveEventEntity(repo, entity); - } - - async getBlockEvents (blockHash: string, where: Where, queryOptions: QueryOptions): Promise { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getBlockEvents(repo, blockHash, where, queryOptions); - } - - async saveBlockWithEvents (queryRunner: QueryRunner, block: DeepPartial, events: DeepPartial[]): Promise { - const blockRepo = queryRunner.manager.getRepository(BlockProgress); - const eventRepo = queryRunner.manager.getRepository(Event); - - return this._baseDatabase.saveBlockWithEvents(blockRepo, eventRepo, block, events); - } - - async saveEvents (queryRunner: QueryRunner, events: Event[]): Promise { - const eventRepo = queryRunner.manager.getRepository(Event); - - return this._baseDatabase.saveEvents(eventRepo, events); - } - - async saveBlockProgress (queryRunner: QueryRunner, block: DeepPartial): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.saveBlockProgress(repo, block); - } - - async saveContract (queryRunner: QueryRunner, address: string, kind: string, checkpoint: boolean, startingBlock: number): Promise { - const repo = queryRunner.manager.getRepository(Contract); - - return this._baseDatabase.saveContract(repo, address, kind, checkpoint, startingBlock); - } - - async updateSyncStatusIndexedBlock (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusIndexedBlock(repo, blockHash, blockNumber, force); - } - - async updateSyncStatusCanonicalBlock (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusCanonicalBlock(repo, blockHash, blockNumber, force); - } - - async updateSyncStatusChainHead (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusChainHead(repo, blockHash, blockNumber, force); - } - - async getSyncStatus (queryRunner: QueryRunner): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.getSyncStatus(repo); - } - - async getEvent (id: string): Promise { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getEvent(repo, id); - } - - async getBlocksAtHeight (height: number, isPruned: boolean): Promise { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getBlocksAtHeight(repo, height, isPruned); - } - - async markBlocksAsPruned (queryRunner: QueryRunner, blocks: BlockProgress[]): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.markBlocksAsPruned(repo, blocks); - } - - async getBlockProgress (blockHash: string): Promise { - const repo = this._conn.getRepository(BlockProgress); - return this._baseDatabase.getBlockProgress(repo, blockHash); - } - - async getBlockProgressEntities (where: FindConditions, options: FindManyOptions): Promise { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getBlockProgressEntities(repo, where, options); - } - - async getEntitiesForBlock (blockHash: string, tableName: string): Promise { - return this._baseDatabase.getEntitiesForBlock(blockHash, tableName); - } - - async updateBlockProgress (queryRunner: QueryRunner, block: BlockProgress, lastProcessedEventIndex: number): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.updateBlockProgress(repo, block, lastProcessedEventIndex); - } - - async removeEntities (queryRunner: QueryRunner, entity: new () => Entity, findConditions?: FindManyOptions | FindConditions): Promise { - return this._baseDatabase.removeEntities(queryRunner, entity, findConditions); - } - - async deleteEntitiesByConditions (queryRunner: QueryRunner, entity: EntityTarget, findConditions: FindConditions): Promise { - await this._baseDatabase.deleteEntitiesByConditions(queryRunner, entity, findConditions); - } - - async getAncestorAtDepth (blockHash: string, depth: number): Promise { - return this._baseDatabase.getAncestorAtDepth(blockHash, depth); - } - - _getPropertyColumnMapForEntity (entityName: string): Map { - return this._conn.getMetadata(entityName).ownColumns.reduce((acc, curr) => { - return acc.set(curr.propertyName, curr.databaseName); - }, new Map()); - } - - _setPropColMaps (): void { - this._propColMaps.MultiNonce = this._getPropertyColumnMapForEntity('MultiNonce'); - this._propColMaps._Owner = this._getPropertyColumnMapForEntity('_Owner'); - this._propColMaps.IsRevoked = this._getPropertyColumnMapForEntity('IsRevoked'); - this._propColMaps.IsPhisher = this._getPropertyColumnMapForEntity('IsPhisher'); - this._propColMaps.IsMember = this._getPropertyColumnMapForEntity('IsMember'); - } -} diff --git a/packages/mobymask-v2-watcher/src/entity/BlockProgress.ts b/packages/mobymask-v2-watcher/src/entity/BlockProgress.ts deleted file mode 100644 index eb9c4832..00000000 --- a/packages/mobymask-v2-watcher/src/entity/BlockProgress.ts +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, CreateDateColumn } from 'typeorm'; -import { BlockProgressInterface } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash'], { unique: true }) -@Index(['blockNumber']) -@Index(['parentHash']) -export class BlockProgress implements BlockProgressInterface { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar') - cid!: string; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('varchar', { length: 66 }) - parentHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('integer') - blockTimestamp!: number; - - @Column('integer') - numEvents!: number; - - @Column('integer') - numProcessedEvents!: number; - - @Column('integer') - lastProcessedEventIndex!: number; - - @Column('boolean') - isComplete!: boolean; - - @Column('boolean', { default: false }) - isPruned!: boolean; - - @CreateDateColumn() - createdAt!: Date; -} diff --git a/packages/mobymask-v2-watcher/src/entity/Contract.ts b/packages/mobymask-v2-watcher/src/entity/Contract.ts deleted file mode 100644 index 9324a578..00000000 --- a/packages/mobymask-v2-watcher/src/entity/Contract.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['address'], { unique: true }) -export class Contract { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 42 }) - address!: string; - - @Column('varchar') - kind!: string; - - @Column('boolean') - checkpoint!: boolean; - - @Column('integer') - startingBlock!: number; -} diff --git a/packages/mobymask-v2-watcher/src/entity/Event.ts b/packages/mobymask-v2-watcher/src/entity/Event.ts deleted file mode 100644 index 28031fb5..00000000 --- a/packages/mobymask-v2-watcher/src/entity/Event.ts +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, ManyToOne } from 'typeorm'; -import { BlockProgress } from './BlockProgress'; - -@Entity() -@Index(['block', 'contract']) -@Index(['block', 'contract', 'eventName']) -export class Event { - @PrimaryGeneratedColumn() - id!: number; - - @ManyToOne(() => BlockProgress, { onDelete: 'CASCADE' }) - block!: BlockProgress; - - @Column('varchar', { length: 66 }) - txHash!: string; - - @Column('integer') - index!: number; - - @Column('varchar', { length: 42 }) - contract!: string; - - @Column('varchar', { length: 256 }) - eventName!: string; - - @Column('text') - eventInfo!: string; - - @Column('text') - extraInfo!: string; - - @Column('text') - proof!: string; -} diff --git a/packages/mobymask-v2-watcher/src/entity/IsMember.ts b/packages/mobymask-v2-watcher/src/entity/IsMember.ts deleted file mode 100644 index 42db6af6..00000000 --- a/packages/mobymask-v2-watcher/src/entity/IsMember.ts +++ /dev/null @@ -1,30 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'key0'], { unique: true }) -export class IsMember { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - key0!: string; - - @Column('boolean') - value!: boolean; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/mobymask-v2-watcher/src/entity/IsPhisher.ts b/packages/mobymask-v2-watcher/src/entity/IsPhisher.ts deleted file mode 100644 index df20a2b8..00000000 --- a/packages/mobymask-v2-watcher/src/entity/IsPhisher.ts +++ /dev/null @@ -1,30 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'key0'], { unique: true }) -export class IsPhisher { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - key0!: string; - - @Column('boolean') - value!: boolean; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/mobymask-v2-watcher/src/entity/IsRevoked.ts b/packages/mobymask-v2-watcher/src/entity/IsRevoked.ts deleted file mode 100644 index 51738524..00000000 --- a/packages/mobymask-v2-watcher/src/entity/IsRevoked.ts +++ /dev/null @@ -1,30 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'key0'], { unique: true }) -export class IsRevoked { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - key0!: string; - - @Column('boolean') - value!: boolean; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/mobymask-v2-watcher/src/entity/MultiNonce.ts b/packages/mobymask-v2-watcher/src/entity/MultiNonce.ts deleted file mode 100644 index 7bdc09b4..00000000 --- a/packages/mobymask-v2-watcher/src/entity/MultiNonce.ts +++ /dev/null @@ -1,34 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'key0', 'key1'], { unique: true }) -export class MultiNonce { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar', { length: 42 }) - key0!: string; - - @Column('numeric', { transformer: bigintTransformer }) - key1!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - value!: bigint; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/mobymask-v2-watcher/src/entity/State.ts b/packages/mobymask-v2-watcher/src/entity/State.ts deleted file mode 100644 index db43d792..00000000 --- a/packages/mobymask-v2-watcher/src/entity/State.ts +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, ManyToOne } from 'typeorm'; - -import { StateKind } from '@cerc-io/util'; - -import { BlockProgress } from './BlockProgress'; - -@Entity() -@Index(['cid'], { unique: true }) -@Index(['block', 'contractAddress']) -@Index(['block', 'contractAddress', 'kind'], { unique: true }) -export class State { - @PrimaryGeneratedColumn() - id!: number; - - @ManyToOne(() => BlockProgress, { onDelete: 'CASCADE' }) - block!: BlockProgress; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - cid!: string; - - @Column({ - type: 'enum', - enum: StateKind - }) - kind!: StateKind; - - @Column('bytea') - data!: Buffer; -} diff --git a/packages/mobymask-v2-watcher/src/entity/StateSyncStatus.ts b/packages/mobymask-v2-watcher/src/entity/StateSyncStatus.ts deleted file mode 100644 index de639d93..00000000 --- a/packages/mobymask-v2-watcher/src/entity/StateSyncStatus.ts +++ /dev/null @@ -1,17 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; - -@Entity() -export class StateSyncStatus { - @PrimaryGeneratedColumn() - id!: number; - - @Column('integer') - latestIndexedBlockNumber!: number; - - @Column('integer', { nullable: true }) - latestCheckpointBlockNumber!: number; -} diff --git a/packages/mobymask-v2-watcher/src/entity/SyncStatus.ts b/packages/mobymask-v2-watcher/src/entity/SyncStatus.ts deleted file mode 100644 index 87896a54..00000000 --- a/packages/mobymask-v2-watcher/src/entity/SyncStatus.ts +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; -import { SyncStatusInterface } from '@cerc-io/util'; - -@Entity() -export class SyncStatus implements SyncStatusInterface { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - chainHeadBlockHash!: string; - - @Column('integer') - chainHeadBlockNumber!: number; - - @Column('varchar', { length: 66 }) - latestIndexedBlockHash!: string; - - @Column('integer') - latestIndexedBlockNumber!: number; - - @Column('varchar', { length: 66 }) - latestCanonicalBlockHash!: string; - - @Column('integer') - latestCanonicalBlockNumber!: number; - - @Column('varchar', { length: 66 }) - initialIndexedBlockHash!: string; - - @Column('integer') - initialIndexedBlockNumber!: number; -} diff --git a/packages/mobymask-v2-watcher/src/entity/_Owner.ts b/packages/mobymask-v2-watcher/src/entity/_Owner.ts deleted file mode 100644 index 82eb0682..00000000 --- a/packages/mobymask-v2-watcher/src/entity/_Owner.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockHash', 'contractAddress'], { unique: true }) -export class _Owner { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - value!: string; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/mobymask-v2-watcher/src/fill.ts b/packages/mobymask-v2-watcher/src/fill.ts deleted file mode 100644 index cbf9146a..00000000 --- a/packages/mobymask-v2-watcher/src/fill.ts +++ /dev/null @@ -1,32 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { FillCmd } from '@cerc-io/cli'; - -import { Database } from './database'; -import { Indexer } from './indexer'; - -const log = debug('vulcanize:fill'); - -export const main = async (): Promise => { - const fillCmd = new FillCmd(); - await fillCmd.init(Database); - await fillCmd.initIndexer(Indexer); - - await fillCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(); -}); - -process.on('SIGINT', () => { - log(`Exiting process ${process.pid} with code 0`); - process.exit(0); -}); diff --git a/packages/mobymask-v2-watcher/src/gql/index.ts b/packages/mobymask-v2-watcher/src/gql/index.ts deleted file mode 100644 index 4732f682..00000000 --- a/packages/mobymask-v2-watcher/src/gql/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * as mutations from './mutations'; -export * as queries from './queries'; -export * as subscriptions from './subscriptions'; diff --git a/packages/mobymask-v2-watcher/src/gql/mutations/index.ts b/packages/mobymask-v2-watcher/src/gql/mutations/index.ts deleted file mode 100644 index 0c3bd853..00000000 --- a/packages/mobymask-v2-watcher/src/gql/mutations/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -import fs from 'fs'; -import path from 'path'; - -export const watchContract = fs.readFileSync(path.join(__dirname, 'watchContract.gql'), 'utf8'); diff --git a/packages/mobymask-v2-watcher/src/gql/mutations/watchContract.gql b/packages/mobymask-v2-watcher/src/gql/mutations/watchContract.gql deleted file mode 100644 index 2ecc74f7..00000000 --- a/packages/mobymask-v2-watcher/src/gql/mutations/watchContract.gql +++ /dev/null @@ -1,3 +0,0 @@ -mutation watchContract($address: String!, $kind: String!, $checkpoint: Boolean!, $startingBlock: Int){ - watchContract(address: $address, kind: $kind, checkpoint: $checkpoint, startingBlock: $startingBlock) -} \ No newline at end of file diff --git a/packages/mobymask-v2-watcher/src/gql/queries/_owner.gql b/packages/mobymask-v2-watcher/src/gql/queries/_owner.gql deleted file mode 100644 index 90154467..00000000 --- a/packages/mobymask-v2-watcher/src/gql/queries/_owner.gql +++ /dev/null @@ -1,8 +0,0 @@ -query _owner($blockHash: String!, $contractAddress: String!){ - _owner(blockHash: $blockHash, contractAddress: $contractAddress){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/mobymask-v2-watcher/src/gql/queries/events.gql b/packages/mobymask-v2-watcher/src/gql/queries/events.gql deleted file mode 100644 index eb41f427..00000000 --- a/packages/mobymask-v2-watcher/src/gql/queries/events.gql +++ /dev/null @@ -1,40 +0,0 @@ -query events($blockHash: String!, $contractAddress: String!, $name: String){ - events(blockHash: $blockHash, contractAddress: $contractAddress, name: $name){ - block{ - cid - hash - number - timestamp - parentHash - } - tx{ - hash - index - from - to - } - contract - eventIndex - event{ - ... on DelegationTriggeredEvent { - principal - agent - } - ... on MemberStatusUpdatedEvent { - entity - isMember - } - ... on OwnershipTransferredEvent { - previousOwner - newOwner - } - ... on PhisherStatusUpdatedEvent { - entity - isPhisher - } - } - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/mobymask-v2-watcher/src/gql/queries/eventsInRange.gql b/packages/mobymask-v2-watcher/src/gql/queries/eventsInRange.gql deleted file mode 100644 index 42e16f6a..00000000 --- a/packages/mobymask-v2-watcher/src/gql/queries/eventsInRange.gql +++ /dev/null @@ -1,40 +0,0 @@ -query eventsInRange($fromBlockNumber: Int!, $toBlockNumber: Int!){ - eventsInRange(fromBlockNumber: $fromBlockNumber, toBlockNumber: $toBlockNumber){ - block{ - cid - hash - number - timestamp - parentHash - } - tx{ - hash - index - from - to - } - contract - eventIndex - event{ - ... on DelegationTriggeredEvent { - principal - agent - } - ... on MemberStatusUpdatedEvent { - entity - isMember - } - ... on OwnershipTransferredEvent { - previousOwner - newOwner - } - ... on PhisherStatusUpdatedEvent { - entity - isPhisher - } - } - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/mobymask-v2-watcher/src/gql/queries/getState.gql b/packages/mobymask-v2-watcher/src/gql/queries/getState.gql deleted file mode 100644 index 3b8f6050..00000000 --- a/packages/mobymask-v2-watcher/src/gql/queries/getState.gql +++ /dev/null @@ -1,15 +0,0 @@ -query getState($blockHash: String!, $contractAddress: String!, $kind: String){ - getState(blockHash: $blockHash, contractAddress: $contractAddress, kind: $kind){ - block{ - cid - hash - number - timestamp - parentHash - } - contractAddress - cid - kind - data - } -} \ No newline at end of file diff --git a/packages/mobymask-v2-watcher/src/gql/queries/getStateByCID.gql b/packages/mobymask-v2-watcher/src/gql/queries/getStateByCID.gql deleted file mode 100644 index 6c3c4fd8..00000000 --- a/packages/mobymask-v2-watcher/src/gql/queries/getStateByCID.gql +++ /dev/null @@ -1,15 +0,0 @@ -query getStateByCID($cid: String!){ - getStateByCID(cid: $cid){ - block{ - cid - hash - number - timestamp - parentHash - } - contractAddress - cid - kind - data - } -} \ No newline at end of file diff --git a/packages/mobymask-v2-watcher/src/gql/queries/index.ts b/packages/mobymask-v2-watcher/src/gql/queries/index.ts deleted file mode 100644 index bdcdde02..00000000 --- a/packages/mobymask-v2-watcher/src/gql/queries/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -import fs from 'fs'; -import path from 'path'; - -export const events = fs.readFileSync(path.join(__dirname, 'events.gql'), 'utf8'); -export const eventsInRange = fs.readFileSync(path.join(__dirname, 'eventsInRange.gql'), 'utf8'); -export const multiNonce = fs.readFileSync(path.join(__dirname, 'multiNonce.gql'), 'utf8'); -export const _owner = fs.readFileSync(path.join(__dirname, '_owner.gql'), 'utf8'); -export const isRevoked = fs.readFileSync(path.join(__dirname, 'isRevoked.gql'), 'utf8'); -export const isPhisher = fs.readFileSync(path.join(__dirname, 'isPhisher.gql'), 'utf8'); -export const isMember = fs.readFileSync(path.join(__dirname, 'isMember.gql'), 'utf8'); -export const getStateByCID = fs.readFileSync(path.join(__dirname, 'getStateByCID.gql'), 'utf8'); -export const getState = fs.readFileSync(path.join(__dirname, 'getState.gql'), 'utf8'); diff --git a/packages/mobymask-v2-watcher/src/gql/queries/isMember.gql b/packages/mobymask-v2-watcher/src/gql/queries/isMember.gql deleted file mode 100644 index f783ec3a..00000000 --- a/packages/mobymask-v2-watcher/src/gql/queries/isMember.gql +++ /dev/null @@ -1,8 +0,0 @@ -query isMember($blockHash: String!, $contractAddress: String!, $key0: String!){ - isMember(blockHash: $blockHash, contractAddress: $contractAddress, key0: $key0){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/mobymask-v2-watcher/src/gql/queries/isPhisher.gql b/packages/mobymask-v2-watcher/src/gql/queries/isPhisher.gql deleted file mode 100644 index 0f4ff6ee..00000000 --- a/packages/mobymask-v2-watcher/src/gql/queries/isPhisher.gql +++ /dev/null @@ -1,8 +0,0 @@ -query isPhisher($blockHash: String!, $contractAddress: String!, $key0: String!){ - isPhisher(blockHash: $blockHash, contractAddress: $contractAddress, key0: $key0){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/mobymask-v2-watcher/src/gql/queries/isRevoked.gql b/packages/mobymask-v2-watcher/src/gql/queries/isRevoked.gql deleted file mode 100644 index 5e1ed69e..00000000 --- a/packages/mobymask-v2-watcher/src/gql/queries/isRevoked.gql +++ /dev/null @@ -1,8 +0,0 @@ -query isRevoked($blockHash: String!, $contractAddress: String!, $key0: String!){ - isRevoked(blockHash: $blockHash, contractAddress: $contractAddress, key0: $key0){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/mobymask-v2-watcher/src/gql/queries/multiNonce.gql b/packages/mobymask-v2-watcher/src/gql/queries/multiNonce.gql deleted file mode 100644 index 9bc400b1..00000000 --- a/packages/mobymask-v2-watcher/src/gql/queries/multiNonce.gql +++ /dev/null @@ -1,8 +0,0 @@ -query multiNonce($blockHash: String!, $contractAddress: String!, $key0: String!, $key1: BigInt!){ - multiNonce(blockHash: $blockHash, contractAddress: $contractAddress, key0: $key0, key1: $key1){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/mobymask-v2-watcher/src/gql/subscriptions/index.ts b/packages/mobymask-v2-watcher/src/gql/subscriptions/index.ts deleted file mode 100644 index f12910c5..00000000 --- a/packages/mobymask-v2-watcher/src/gql/subscriptions/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -import fs from 'fs'; -import path from 'path'; - -export const onEvent = fs.readFileSync(path.join(__dirname, 'onEvent.gql'), 'utf8'); diff --git a/packages/mobymask-v2-watcher/src/gql/subscriptions/onEvent.gql b/packages/mobymask-v2-watcher/src/gql/subscriptions/onEvent.gql deleted file mode 100644 index cff8741a..00000000 --- a/packages/mobymask-v2-watcher/src/gql/subscriptions/onEvent.gql +++ /dev/null @@ -1,40 +0,0 @@ -subscription onEvent{ - onEvent{ - block{ - cid - hash - number - timestamp - parentHash - } - tx{ - hash - index - from - to - } - contract - eventIndex - event{ - ... on DelegationTriggeredEvent { - principal - agent - } - ... on MemberStatusUpdatedEvent { - entity - isMember - } - ... on OwnershipTransferredEvent { - previousOwner - newOwner - } - ... on PhisherStatusUpdatedEvent { - entity - isPhisher - } - } - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/mobymask-v2-watcher/src/hooks.ts b/packages/mobymask-v2-watcher/src/hooks.ts deleted file mode 100644 index 8f978b67..00000000 --- a/packages/mobymask-v2-watcher/src/hooks.ts +++ /dev/null @@ -1,129 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import assert from 'assert'; -import { utils } from 'ethers'; - -import { ResultEvent } from '@cerc-io/util'; - -import { Indexer, KIND_PHISHERREGISTRY } from './indexer'; - -const INVOKE_SIGNATURE = 'invoke(((((address,uint256,bytes),((address,bytes32,(address,bytes)[]),bytes)[])[],(uint256,uint256)),bytes)[])'; -const CLAIM_IF_MEMBER_SIGNATURE = 'claimIfMember(string,bool)'; -const CLAIM_IF_PHISHER_SIGNATURE = 'claimIfPhisher(string,bool)'; - -/** - * Hook function to store an initial state. - * @param indexer Indexer instance. - * @param blockHash Hash of the concerned block. - * @param contractAddress Address of the concerned contract. - * @returns Data block to be stored. - */ -export async function createInitialState (indexer: Indexer, contractAddress: string, blockHash: string): Promise { - assert(indexer); - assert(blockHash); - assert(contractAddress); - - // Store an empty State. - const stateData: any = { - state: {} - }; - - // Use updateStateForElementaryType to update initial state with an elementary property. - // Eg. const stateData = updateStateForElementaryType(stateData, '_totalBalance', result.value.toString()); - - // Use updateStateForMappingType to update initial state with a nested property. - // Eg. const stateData = updateStateForMappingType(stateData, '_allowances', [owner, spender], allowance.value.toString()); - - // Return initial state data to be saved. - return stateData; -} - -/** - * Hook function to create state diff. - * @param indexer Indexer instance that contains methods to fetch the contract varaiable values. - * @param blockHash Block hash of the concerned block. - */ -export async function createStateDiff (indexer: Indexer, blockHash: string): Promise { - assert(indexer); - assert(blockHash); - - // Use indexer.createDiff() method to save custom state diff(s). -} - -/** - * Hook function to create state checkpoint - * @param indexer Indexer instance. - * @param contractAddress Address of the concerned contract. - * @param blockHash Block hash of the concerned block. - * @returns Whether to disable default checkpoint. If false, the state from this hook is updated with that from default checkpoint. - */ -export async function createStateCheckpoint (indexer: Indexer, contractAddress: string, blockHash: string): Promise { - assert(indexer); - assert(blockHash); - assert(contractAddress); - - // Use indexer.createStateCheckpoint() method to create a custom checkpoint. - - // Return false to update the state created by this hook by auto-generated checkpoint state. - // Return true to disable update of the state created by this hook by auto-generated checkpoint state. - return false; -} - -/** - * Event hook function. - * @param indexer Indexer instance that contains methods to fetch and update the contract values in the database. - * @param eventData ResultEvent object containing event information. - */ -export async function handleEvent (indexer: Indexer, eventData: ResultEvent): Promise { - assert(indexer); - assert(eventData); - - // Perform indexing for PhisherStatusUpdated and MemberStatusUpdated. - if (['PhisherStatusUpdatedEvent', 'MemberStatusUpdatedEvent'].includes(eventData.event.__typename)) { - const txData = await indexer.getFullTransaction(eventData.tx.hash, eventData.block.number); - const txDescription = getTxDescription(indexer, KIND_PHISHERREGISTRY, txData.input); - let txDescriptions = [txDescription]; - - if (txDescription.signature === INVOKE_SIGNATURE) { - // Parse transactions from batches if it is an invoke method in Delegatable contract. - txDescriptions = txDescription.args.signedInvocations - .reduce((txs: utils.TransactionDescription[], signedInvocation: any) => { - // Get transactions from signed invocations batch. - const batchTxs = signedInvocation.invocations.batch.map((invocation: any) => { - return getTxDescription(indexer, KIND_PHISHERREGISTRY, invocation.transaction.data); - }); - - txs.push(...batchTxs); - - return txs; - }, []); - } - - // Filter transactions for claimIfMember and claimIsPhisher methods. - txDescriptions = txDescriptions.filter((tx: utils.TransactionDescription) => { - return [CLAIM_IF_MEMBER_SIGNATURE, CLAIM_IF_PHISHER_SIGNATURE].includes(tx.signature); - }); - - for (const txDescription of txDescriptions) { - switch (txDescription.signature) { - case CLAIM_IF_MEMBER_SIGNATURE: - // Update isMember entry for the identifier in database. - await indexer.isMember(eventData.block.hash, eventData.contract, txDescription.args.identifier, true); - break; - case CLAIM_IF_PHISHER_SIGNATURE: - // Update isPhisher entry for the identifier in database. - await indexer.isPhisher(eventData.block.hash, eventData.contract, txDescription.args.identifier, true); - break; - } - } - } -} - -// Get transaction details from input data. -const getTxDescription = (indexer: Indexer, contractKind: string, data: string): utils.TransactionDescription => { - const contractInterface = indexer.getContractInterface(contractKind); - assert(contractInterface); - return contractInterface.parseTransaction({ data }); -}; diff --git a/packages/mobymask-v2-watcher/src/indexer.ts b/packages/mobymask-v2-watcher/src/indexer.ts deleted file mode 100644 index 50c993af..00000000 --- a/packages/mobymask-v2-watcher/src/indexer.ts +++ /dev/null @@ -1,713 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import assert from 'assert'; -import debug from 'debug'; -import { DeepPartial, FindConditions, FindManyOptions } from 'typeorm'; -import JSONbig from 'json-bigint'; -import { ethers } from 'ethers'; - -import { JsonFragment } from '@ethersproject/abi'; -import { JsonRpcProvider } from '@ethersproject/providers'; -import { EthClient } from '@cerc-io/ipld-eth-client'; -import { MappingKey, StorageLayout, getStorageValue } from '@cerc-io/solidity-mapper'; -import { - Indexer as BaseIndexer, - IndexerInterface, - ValueResult, - ServerConfig, - JobQueue, - Where, - QueryOptions, - updateStateForElementaryType, - updateStateForMappingType, - BlockHeight, - StateKind, - StateStatus, - getFullTransaction, - ResultEvent, - getResultEvent, - DatabaseInterface, - Clients -} from '@cerc-io/util'; - -import PhisherRegistryArtifacts from './artifacts/PhisherRegistry.json'; -import { Database, ENTITIES } from './database'; -import { createInitialState, handleEvent, createStateDiff, createStateCheckpoint } from './hooks'; -import { Contract } from './entity/Contract'; -import { Event } from './entity/Event'; -import { SyncStatus } from './entity/SyncStatus'; -import { StateSyncStatus } from './entity/StateSyncStatus'; -import { BlockProgress } from './entity/BlockProgress'; -import { State } from './entity/State'; -import { IsMember } from './entity/IsMember'; -import { IsPhisher } from './entity/IsPhisher'; -import { IsRevoked } from './entity/IsRevoked'; -import { _Owner } from './entity/_Owner'; -import { MultiNonce } from './entity/MultiNonce'; - -const log = debug('vulcanize:indexer'); -const JSONbigNative = JSONbig({ useNativeBigInt: true }); - -export const KIND_PHISHERREGISTRY = 'PhisherRegistry'; - -export class Indexer implements IndexerInterface { - _db: Database; - _ethClient: EthClient; - _ethProvider: JsonRpcProvider; - _baseIndexer: BaseIndexer; - _serverConfig: ServerConfig; - - _abiMap: Map; - _storageLayoutMap: Map; - _contractMap: Map; - - constructor (serverConfig: ServerConfig, db: DatabaseInterface, clients: Clients, ethProvider: JsonRpcProvider, jobQueue: JobQueue) { - assert(db); - assert(clients.ethClient); - - this._db = db as Database; - this._ethClient = clients.ethClient; - this._ethProvider = ethProvider; - this._serverConfig = serverConfig; - this._baseIndexer = new BaseIndexer(this._serverConfig, this._db, this._ethClient, this._ethProvider, jobQueue); - - this._abiMap = new Map(); - this._storageLayoutMap = new Map(); - this._contractMap = new Map(); - - const { - abi: PhisherRegistryABI, - storageLayout: PhisherRegistryStorageLayout - } = PhisherRegistryArtifacts; - - assert(PhisherRegistryABI); - this._abiMap.set(KIND_PHISHERREGISTRY, PhisherRegistryABI); - assert(PhisherRegistryStorageLayout); - this._storageLayoutMap.set(KIND_PHISHERREGISTRY, PhisherRegistryStorageLayout); - this._contractMap.set(KIND_PHISHERREGISTRY, new ethers.utils.Interface(PhisherRegistryABI)); - } - - get serverConfig (): ServerConfig { - return this._serverConfig; - } - - get storageLayoutMap (): Map { - return this._storageLayoutMap; - } - - async init (): Promise { - await this._baseIndexer.fetchContracts(); - await this._baseIndexer.fetchStateStatus(); - } - - getResultEvent (event: Event): ResultEvent { - return getResultEvent(event); - } - - async multiNonce (blockHash: string, contractAddress: string, key0: string, key1: bigint, diff = false): Promise { - let entity = await this._db.getMultiNonce({ blockHash, contractAddress, key0, key1 }); - - if (entity) { - log('multiNonce: db hit.'); - } else { - log('multiNonce: db miss, fetching from upstream server'); - - entity = await this._getStorageEntity( - blockHash, - contractAddress, - MultiNonce, - 'multiNonce', - { key0, key1 }, - BigInt(0) - ); - - await this._db.saveMultiNonce(entity); - - if (diff) { - const stateUpdate = updateStateForMappingType({}, 'multiNonce', [key0.toString(), key1.toString()], entity.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - } - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - async _owner (blockHash: string, contractAddress: string, diff = false): Promise { - let entity = await this._db._getOwner({ blockHash, contractAddress }); - - if (entity) { - log('_owner: db hit.'); - } else { - log('_owner: db miss, fetching from upstream server'); - - entity = await this._getStorageEntity( - blockHash, - contractAddress, - _Owner, - '_owner', - {}, - '' - ); - - await this._db._saveOwner(entity); - - if (diff) { - const stateUpdate = updateStateForElementaryType({}, '_owner', entity.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - } - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - async isRevoked (blockHash: string, contractAddress: string, key0: string, diff = false): Promise { - let entity = await this._db.getIsRevoked({ blockHash, contractAddress, key0 }); - - if (entity) { - log('isRevoked: db hit.'); - } else { - log('isRevoked: db miss, fetching from upstream server'); - - entity = await this._getStorageEntity( - blockHash, - contractAddress, - IsRevoked, - 'isRevoked', - { key0 }, - false - ); - - await this._db.saveIsRevoked(entity); - - if (diff) { - const stateUpdate = updateStateForMappingType({}, 'isRevoked', [key0.toString()], entity.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - } - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - async isPhisher (blockHash: string, contractAddress: string, key0: string, diff = false): Promise { - let entity = await this._db.getIsPhisher({ blockHash, contractAddress, key0 }); - - if (entity) { - log('isPhisher: db hit.'); - } else { - log('isPhisher: db miss, fetching from upstream server'); - - entity = await this._getStorageEntity( - blockHash, - contractAddress, - IsPhisher, - 'isPhisher', - { key0 }, - false - ); - - await this._db.saveIsPhisher(entity); - - if (diff) { - const stateUpdate = updateStateForMappingType({}, 'isPhisher', [key0.toString()], entity.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - } - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - async isMember (blockHash: string, contractAddress: string, key0: string, diff = false): Promise { - let entity = await this._db.getIsMember({ blockHash, contractAddress, key0 }); - - if (entity) { - log('isMember: db hit.'); - } else { - log('isMember: db miss, fetching from upstream server'); - - entity = await this._getStorageEntity( - blockHash, - contractAddress, - IsMember, - 'isMember', - { key0 }, - false - ); - - await this._db.saveIsMember(entity); - - if (diff) { - const stateUpdate = updateStateForMappingType({}, 'isMember', [key0.toString()], entity.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - } - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - async _getStorageEntity ( - blockHash: string, - contractAddress: string, - entity: new () => Entity, - storageVariableName: string, - mappingKeys: {[key: string]: any}, - defaultValue: any - ): Promise { - const [{ number }, syncStatus] = await Promise.all([ - // Laconicd doesn't support eth_getHeaderByHash - // this._ethProvider.send('eth_getHeaderByHash', [blockHash]), - this._ethProvider.getBlock(blockHash), - this.getSyncStatus() - ]); - - // const blockNumber = ethers.BigNumber.from(number).toNumber(); - const blockNumber = number; - - let result: ValueResult = { - value: defaultValue - }; - - if (syncStatus && blockNumber < syncStatus.initialIndexedBlockNumber) { - const entityFields: any = { blockNumber, contractAddress, ...mappingKeys }; - const entityData: any = await this._db.getPrevEntity(entity, entityFields); - - if (entityData) { - result = { - value: entityData.value, - proof: JSON.parse(entityData.proof) - }; - } - } else { - const storageLayout = this._storageLayoutMap.get(KIND_PHISHERREGISTRY); - assert(storageLayout); - - // Get storage value using ipld-eth-server - // result = await this._baseIndexer.getStorageValue( - // storageLayout, - // blockHash, - // contractAddress, - // storageVariableName, - // ...Object.values(mappingKeys) - // ); - - // Get storage value using ETH RPC endpoint - result = await this._getStorageValueRPC( - storageLayout, - blockHash, - contractAddress, - storageVariableName, - ...Object.values(mappingKeys) - ); - } - - return { - blockHash, - blockNumber, - contractAddress, - ...mappingKeys, - value: result.value, - proof: result.proof ? JSONbigNative.stringify(result.proof) : null - } as any; - } - - async _getStorageValueRPC (storageLayout: StorageLayout, blockHash: string, contractAddress: string, variable: string, ...mappingKeys: MappingKey[]): Promise { - const getStorageAt = async (params: { blockHash: string, contract: string, slot: string }) => { - const { blockHash, contract, slot } = params; - const value = await this._ethProvider.getStorageAt(contract, slot, blockHash); - - return { - value, - proof: { - // Returning null value as proof, since ethers library getStorageAt method doesn't return proof. - data: JSON.stringify(null) - } - }; - }; - - return getStorageValue( - storageLayout, - getStorageAt, - blockHash, - contractAddress, - variable, - ...mappingKeys - ); - } - - async getStorageValue (storageLayout: StorageLayout, blockHash: string, contractAddress: string, variable: string, ...mappingKeys: MappingKey[]): Promise { - return this._baseIndexer.getStorageValue( - storageLayout, - blockHash, - contractAddress, - variable, - ...mappingKeys - ); - } - - async getEntitiesForBlock (blockHash: string, tableName: string): Promise { - return this._db.getEntitiesForBlock(blockHash, tableName); - } - - async processInitialState (contractAddress: string, blockHash: string): Promise { - // Call initial state hook. - return createInitialState(this, contractAddress, blockHash); - } - - async processStateCheckpoint (contractAddress: string, blockHash: string): Promise { - // Call checkpoint hook. - return createStateCheckpoint(this, contractAddress, blockHash); - } - - async processCanonicalBlock (blockHash: string): Promise { - console.time('time:indexer#processCanonicalBlock-finalize_auto_diffs'); - // Finalize staged diff blocks if any. - await this._baseIndexer.finalizeDiffStaged(blockHash); - console.timeEnd('time:indexer#processCanonicalBlock-finalize_auto_diffs'); - - // Call custom stateDiff hook. - await createStateDiff(this, blockHash); - } - - async processCheckpoint (blockHash: string): Promise { - // Return if checkpointInterval is <= 0. - const checkpointInterval = this._serverConfig.checkpointInterval; - if (checkpointInterval <= 0) return; - - console.time('time:indexer#processCheckpoint-checkpoint'); - await this._baseIndexer.processCheckpoint(this, blockHash, checkpointInterval); - console.timeEnd('time:indexer#processCheckpoint-checkpoint'); - } - - async processCLICheckpoint (contractAddress: string, blockHash?: string): Promise { - return this._baseIndexer.processCLICheckpoint(this, contractAddress, blockHash); - } - - async getPrevState (blockHash: string, contractAddress: string, kind?: string): Promise { - return this._db.getPrevState(blockHash, contractAddress, kind); - } - - async getLatestState (contractAddress: string, kind: StateKind | null, blockNumber?: number): Promise { - return this._db.getLatestState(contractAddress, kind, blockNumber); - } - - async getStatesByHash (blockHash: string): Promise { - return this._baseIndexer.getStatesByHash(blockHash); - } - - async getStateByCID (cid: string): Promise { - return this._baseIndexer.getStateByCID(cid); - } - - async getStates (where: FindConditions): Promise { - return this._db.getStates(where); - } - - getStateData (state: State): any { - return this._baseIndexer.getStateData(state); - } - - // Method used to create auto diffs (diff_staged). - async createDiffStaged (contractAddress: string, blockHash: string, data: any): Promise { - console.time('time:indexer#createDiffStaged-auto_diff'); - await this._baseIndexer.createDiffStaged(contractAddress, blockHash, data); - console.timeEnd('time:indexer#createDiffStaged-auto_diff'); - } - - // Method to be used by createStateDiff hook. - async createDiff (contractAddress: string, blockHash: string, data: any): Promise { - const block = await this.getBlockProgress(blockHash); - assert(block); - - await this._baseIndexer.createDiff(contractAddress, block, data); - } - - // Method to be used by createStateCheckpoint hook. - async createStateCheckpoint (contractAddress: string, blockHash: string, data: any): Promise { - const block = await this.getBlockProgress(blockHash); - assert(block); - - return this._baseIndexer.createStateCheckpoint(contractAddress, block, data); - } - - // Method to be used by export-state CLI. - async createCheckpoint (contractAddress: string, blockHash: string): Promise { - const block = await this.getBlockProgress(blockHash); - assert(block); - - return this._baseIndexer.createCheckpoint(this, contractAddress, block); - } - - async saveOrUpdateState (state: State): Promise { - return this._baseIndexer.saveOrUpdateState(state); - } - - async removeStates (blockNumber: number, kind: StateKind): Promise { - await this._baseIndexer.removeStates(blockNumber, kind); - } - - async triggerIndexingOnEvent (event: Event): Promise { - const resultEvent = this.getResultEvent(event); - - // Call custom hook function for indexing on event. - await handleEvent(this, resultEvent); - } - - async processEvent (event: Event): Promise { - // Trigger indexing of data based on the event. - await this.triggerIndexingOnEvent(event); - } - - async processBlock (blockProgress: BlockProgress): Promise { - console.time('time:indexer#processBlock-init_state'); - // Call a function to create initial state for contracts. - await this._baseIndexer.createInit(this, blockProgress.blockHash, blockProgress.blockNumber); - console.timeEnd('time:indexer#processBlock-init_state'); - } - - parseEventNameAndArgs (kind: string, logObj: any): any { - const { topics, data } = logObj; - - const contract = this._contractMap.get(kind); - assert(contract); - - const logDescription = contract.parseLog({ data, topics }); - - const { eventName, eventInfo, eventSignature } = this._baseIndexer.parseEvent(logDescription); - - return { - eventName, - eventInfo, - eventSignature - }; - } - - async getStateSyncStatus (): Promise { - return this._db.getStateSyncStatus(); - } - - async updateStateSyncStatusIndexedBlock (blockNumber: number, force?: boolean): Promise { - const dbTx = await this._db.createTransactionRunner(); - let res; - - try { - res = await this._db.updateStateSyncStatusIndexedBlock(dbTx, blockNumber, force); - await dbTx.commitTransaction(); - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - - return res; - } - - async updateStateSyncStatusCheckpointBlock (blockNumber: number, force?: boolean): Promise { - const dbTx = await this._db.createTransactionRunner(); - let res; - - try { - res = await this._db.updateStateSyncStatusCheckpointBlock(dbTx, blockNumber, force); - await dbTx.commitTransaction(); - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - - return res; - } - - async getLatestCanonicalBlock (): Promise { - const syncStatus = await this.getSyncStatus(); - assert(syncStatus); - - const latestCanonicalBlock = await this.getBlockProgress(syncStatus.latestCanonicalBlockHash); - assert(latestCanonicalBlock); - - return latestCanonicalBlock; - } - - async getLatestStateIndexedBlock (): Promise { - return this._baseIndexer.getLatestStateIndexedBlock(); - } - - async watchContract (address: string, kind: string, checkpoint: boolean, startingBlock: number): Promise { - return this._baseIndexer.watchContract(address, kind, checkpoint, startingBlock); - } - - updateStateStatusMap (address: string, stateStatus: StateStatus): void { - this._baseIndexer.updateStateStatusMap(address, stateStatus); - } - - cacheContract (contract: Contract): void { - return this._baseIndexer.cacheContract(contract); - } - - async saveEventEntity (dbEvent: Event): Promise { - return this._baseIndexer.saveEventEntity(dbEvent); - } - - async getEventsByFilter (blockHash: string, contract?: string, name?: string): Promise> { - return this._baseIndexer.getEventsByFilter(blockHash, contract, name); - } - - isWatchedContract (address : string): Contract | undefined { - return this._baseIndexer.isWatchedContract(address); - } - - getContractsByKind (kind: string): Contract[] { - return this._baseIndexer.getContractsByKind(kind); - } - - async getProcessedBlockCountForRange (fromBlockNumber: number, toBlockNumber: number): Promise<{ expected: number, actual: number }> { - return this._baseIndexer.getProcessedBlockCountForRange(fromBlockNumber, toBlockNumber); - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise> { - return this._baseIndexer.getEventsInRange(fromBlockNumber, toBlockNumber, this._serverConfig.maxEventsBlockRange); - } - - async getSyncStatus (): Promise { - return this._baseIndexer.getSyncStatus(); - } - - async getBlocks (blockFilter: { blockHash?: string, blockNumber?: number }): Promise { - return this._baseIndexer.getBlocks(blockFilter); - } - - async updateSyncStatusIndexedBlock (blockHash: string, blockNumber: number, force = false): Promise { - return this._baseIndexer.updateSyncStatusIndexedBlock(blockHash, blockNumber, force); - } - - async updateSyncStatusChainHead (blockHash: string, blockNumber: number, force = false): Promise { - return this._baseIndexer.updateSyncStatusChainHead(blockHash, blockNumber, force); - } - - async updateSyncStatusCanonicalBlock (blockHash: string, blockNumber: number, force = false): Promise { - return this._baseIndexer.updateSyncStatusCanonicalBlock(blockHash, blockNumber, force); - } - - async getEvent (id: string): Promise { - return this._baseIndexer.getEvent(id); - } - - async getBlockProgress (blockHash: string): Promise { - return this._baseIndexer.getBlockProgress(blockHash); - } - - async getBlockProgressEntities (where: FindConditions, options: FindManyOptions): Promise { - return this._baseIndexer.getBlockProgressEntities(where, options); - } - - async getBlocksAtHeight (height: number, isPruned: boolean): Promise { - return this._baseIndexer.getBlocksAtHeight(height, isPruned); - } - - async saveBlockAndFetchEvents (block: DeepPartial): Promise<[BlockProgress, DeepPartial[]]> { - return this._saveBlockAndFetchEvents(block); - } - - async getBlockEvents (blockHash: string, where: Where, queryOptions: QueryOptions): Promise> { - return this._baseIndexer.getBlockEvents(blockHash, where, queryOptions); - } - - async removeUnknownEvents (block: BlockProgress): Promise { - return this._baseIndexer.removeUnknownEvents(Event, block); - } - - async markBlocksAsPruned (blocks: BlockProgress[]): Promise { - return this._baseIndexer.markBlocksAsPruned(blocks); - } - - async updateBlockProgress (block: BlockProgress, lastProcessedEventIndex: number): Promise { - return this._baseIndexer.updateBlockProgress(block, lastProcessedEventIndex); - } - - async getAncestorAtDepth (blockHash: string, depth: number): Promise { - return this._baseIndexer.getAncestorAtDepth(blockHash, depth); - } - - // Get latest block using eth provider. - async getLatestBlock (): Promise { - // Use ipld-eth-server - // const { block } = await this._ethClient.getBlockByHash(); - - // Use ETH RPC endpoint - const number = await this._ethProvider.getBlockNumber(); - const { hash } = await this._ethProvider.getBlock(number); - - return { - number, - hash - }; - } - - // Get full transaction data. - async getFullTransaction (txHash: string, blockNumber: number): Promise { - return getFullTransaction(this._ethClient, txHash, blockNumber); - } - - // Get contract interface for specified contract kind. - getContractInterface (kind: string): ethers.utils.Interface | undefined { - return this._contractMap.get(kind); - } - - async resetWatcherToBlock (blockNumber: number): Promise { - const entities = [...ENTITIES]; - await this._baseIndexer.resetWatcherToBlock(blockNumber, entities); - } - - async _saveBlockAndFetchEvents ({ - cid: blockCid, - blockHash, - blockNumber, - blockTimestamp, - parentHash - }: DeepPartial): Promise<[BlockProgress, DeepPartial[]]> { - assert(blockHash); - assert(blockNumber); - - const dbEvents = await this._baseIndexer.fetchEvents(blockHash, blockNumber, this.parseEventNameAndArgs.bind(this)); - - const dbTx = await this._db.createTransactionRunner(); - try { - const block = { - cid: blockCid, - blockHash, - blockNumber, - blockTimestamp, - parentHash - }; - - console.time(`time:indexer#_saveBlockAndFetchEvents-db-save-${blockNumber}`); - const blockProgress = await this._db.saveBlockWithEvents(dbTx, block, dbEvents); - await dbTx.commitTransaction(); - console.timeEnd(`time:indexer#_saveBlockAndFetchEvents-db-save-${blockNumber}`); - - return [blockProgress, []]; - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - } -} diff --git a/packages/mobymask-v2-watcher/src/job-runner.ts b/packages/mobymask-v2-watcher/src/job-runner.ts deleted file mode 100644 index e1356b16..00000000 --- a/packages/mobymask-v2-watcher/src/job-runner.ts +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import debug from 'debug'; - -import { JobRunnerCmd } from '@cerc-io/cli'; -import { JobRunner } from '@cerc-io/util'; - -import { Indexer } from './indexer'; -import { Database } from './database'; - -const log = debug('vulcanize:job-runner'); - -export const main = async (): Promise => { - const jobRunnerCmd = new JobRunnerCmd(); - await jobRunnerCmd.init(Database); - await jobRunnerCmd.initIndexer(Indexer); - - await jobRunnerCmd.exec(async (jobRunner: JobRunner): Promise => { - await jobRunner.subscribeBlockProcessingQueue(); - await jobRunner.subscribeEventProcessingQueue(); - await jobRunner.subscribeBlockCheckpointQueue(); - await jobRunner.subscribeHooksQueue(); - }); -}; - -main().then(() => { - log('Starting job runner...'); -}).catch(err => { - log(err); -}); - -process.on('uncaughtException', err => { - log('uncaughtException', err); -}); diff --git a/packages/mobymask-v2-watcher/src/libp2p-utils.ts b/packages/mobymask-v2-watcher/src/libp2p-utils.ts deleted file mode 100644 index 49299e18..00000000 --- a/packages/mobymask-v2-watcher/src/libp2p-utils.ts +++ /dev/null @@ -1,149 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import debug from 'debug'; -import { ethers, Signer } from 'ethers'; -import { TransactionReceipt, TransactionResponse } from '@ethersproject/providers'; - -import { abi as PhisherRegistryABI } from './artifacts/PhisherRegistry.json'; - -const log = debug('vulcanize:libp2p-utils'); - -const contractInterface = new ethers.utils.Interface(PhisherRegistryABI); - -const MESSAGE_KINDS = { - INVOKE: 'invoke', - REVOKE: 'revoke' -}; - -const DEFAULT_GAS_LIMIT = 500000; - -export function createMessageToL2Handler ( - signer: Signer, - { contractAddress, gasLimit }: { - contractAddress: string, - gasLimit?: number - } -) { - return (peerId: string, data: any): void => { - log(`[${getCurrentTime()}] Received a message on mobymask P2P network from peer:`, peerId); - sendMessageToL2(signer, { contractAddress, gasLimit }, data); - }; -} - -export async function sendMessageToL2 ( - signer: Signer, - { contractAddress, gasLimit = DEFAULT_GAS_LIMIT }: { - contractAddress: string, - gasLimit?: number - }, - data: any -): Promise { - const { kind, message } = data; - const contract = new ethers.Contract(contractAddress, PhisherRegistryABI, signer); - let receipt: TransactionReceipt | undefined; - - try { - switch (kind) { - case MESSAGE_KINDS.INVOKE: { - const signedInvocations = message; - - const transaction: TransactionResponse = await contract.invoke( - signedInvocations, - // Setting gasLimit as eth_estimateGas call takes too long in L2 chain - { gasLimit } - ); - - receipt = await transaction.wait(); - - break; - } - - case MESSAGE_KINDS.REVOKE: { - const { signedDelegation, signedIntendedRevocation } = message; - - const transaction: TransactionResponse = await contract.revokeDelegation( - signedDelegation, - signedIntendedRevocation, - // Setting gasLimit as eth_estimateGas call takes too long in L2 chain - { gasLimit } - ); - - receipt = await transaction.wait(); - - break; - } - - default: { - log(`Handler for libp2p message kind ${kind} not implemented`); - log(JSON.stringify(message, null, 2)); - break; - } - } - - if (receipt) { - log(`Transaction receipt for ${kind} message`, { - to: receipt.to, - blockNumber: receipt.blockNumber, - blockHash: receipt.blockHash, - transactionHash: receipt.transactionHash, - effectiveGasPrice: receipt.effectiveGasPrice.toString(), - gasUsed: receipt.gasUsed.toString() - }); - } - } catch (error) { - log(error); - } -} - -export function parseLibp2pMessage (peerId: string, data: any): void { - log(`[${getCurrentTime()}] Received a message on mobymask P2P network from peer:`, peerId); - const { kind, message } = data; - - switch (kind) { - case MESSAGE_KINDS.INVOKE: { - _parseInvocation(message); - break; - } - - case MESSAGE_KINDS.REVOKE: { - _parseRevocation(message); - break; - } - - default: { - log(`libp2p message of unknown kind ${kind}`); - log(JSON.stringify(message, null, 2)); - break; - } - } - - log('------------------------------------------'); -} - -export const getCurrentTime = (): string => { - const now = new Date(); - return `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`; -}; - -function _parseInvocation (msg: any): void { - log('Signed invocations:'); - log(JSON.stringify(msg, null, 2)); - - const [{ invocations: { batch: invocationsList } }] = msg; - Array.from(invocationsList).forEach((invocation: any) => { - const txData = invocation.transaction.data; - const decoded = contractInterface.parseTransaction({ data: txData }); - - log(`method: ${decoded.name}, value: ${decoded.args[0]}`); - }); -} - -function _parseRevocation (msg: any): void { - const { signedDelegation, signedIntendedRevocation } = msg; - log('Signed delegation:'); - log(JSON.stringify(signedDelegation, null, 2)); - log('Signed intention to revoke:'); - log(JSON.stringify(signedIntendedRevocation, null, 2)); -} diff --git a/packages/mobymask-v2-watcher/src/resolvers.ts b/packages/mobymask-v2-watcher/src/resolvers.ts deleted file mode 100644 index 08d3905b..00000000 --- a/packages/mobymask-v2-watcher/src/resolvers.ts +++ /dev/null @@ -1,160 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import assert from 'assert'; -import BigInt from 'apollo-type-bigint'; -import debug from 'debug'; -import Decimal from 'decimal.js'; -import { GraphQLScalarType } from 'graphql'; - -import { ValueResult, gqlTotalQueryCount, gqlQueryCount, getResultState, IndexerInterface, EventWatcher } from '@cerc-io/util'; - -import { Indexer } from './indexer'; - -const log = debug('vulcanize:resolver'); - -export const createResolvers = async (indexerArg: IndexerInterface, eventWatcher: EventWatcher): Promise => { - const indexer = indexerArg as Indexer; - - return { - BigInt: new BigInt('bigInt'), - - BigDecimal: new GraphQLScalarType({ - name: 'BigDecimal', - description: 'BigDecimal custom scalar type', - parseValue (value) { - // value from the client - return new Decimal(value); - }, - serialize (value: Decimal) { - // value sent to the client - return value.toFixed(); - } - }), - - Event: { - __resolveType: (obj: any) => { - assert(obj.__typename); - - return obj.__typename; - } - }, - - Subscription: { - onEvent: { - subscribe: () => eventWatcher.getEventIterator() - } - }, - - Mutation: { - watchContract: async (_: any, { address, kind, checkpoint, startingBlock = 1 }: { address: string, kind: string, checkpoint: boolean, startingBlock: number }): Promise => { - log('watchContract', address, kind, checkpoint, startingBlock); - await indexer.watchContract(address, kind, checkpoint, startingBlock); - - return true; - } - }, - - Query: { - multiNonce: (_: any, { blockHash, contractAddress, key0, key1 }: { blockHash: string, contractAddress: string, key0: string, key1: bigint }): Promise => { - log('multiNonce', blockHash, contractAddress, key0, key1); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('multiNonce').inc(1); - - return indexer.multiNonce(blockHash, contractAddress, key0, key1); - }, - - _owner: (_: any, { blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise => { - log('_owner', blockHash, contractAddress); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('_owner').inc(1); - - return indexer._owner(blockHash, contractAddress); - }, - - isRevoked: (_: any, { blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: string }): Promise => { - log('isRevoked', blockHash, contractAddress, key0); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('isRevoked').inc(1); - - return indexer.isRevoked(blockHash, contractAddress, key0); - }, - - isPhisher: (_: any, { blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: string }): Promise => { - log('isPhisher', blockHash, contractAddress, key0); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('isPhisher').inc(1); - - return indexer.isPhisher(blockHash, contractAddress, key0); - }, - - isMember: (_: any, { blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: string }): Promise => { - log('isMember', blockHash, contractAddress, key0); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('isMember').inc(1); - - return indexer.isMember(blockHash, contractAddress, key0); - }, - - events: async (_: any, { blockHash, contractAddress, name }: { blockHash: string, contractAddress: string, name?: string }) => { - log('events', blockHash, contractAddress, name); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('events').inc(1); - - const block = await indexer.getBlockProgress(blockHash); - if (!block || !block.isComplete) { - throw new Error(`Block hash ${blockHash} number ${block?.blockNumber} not processed yet`); - } - - const events = await indexer.getEventsByFilter(blockHash, contractAddress, name); - return events.map(event => indexer.getResultEvent(event)); - }, - - eventsInRange: async (_: any, { fromBlockNumber, toBlockNumber }: { fromBlockNumber: number, toBlockNumber: number }) => { - log('eventsInRange', fromBlockNumber, toBlockNumber); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('eventsInRange').inc(1); - - const events = await indexer.getEventsInRange(fromBlockNumber, toBlockNumber); - return events.map(event => indexer.getResultEvent(event)); - }, - - getStateByCID: async (_: any, { cid }: { cid: string }) => { - log('getStateByCID', cid); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('getStateByCID').inc(1); - - const state = await indexer.getStateByCID(cid); - - return state && state.block.isComplete ? getResultState(state) : undefined; - }, - - getState: async (_: any, { blockHash, contractAddress, kind }: { blockHash: string, contractAddress: string, kind: string }) => { - log('getState', blockHash, contractAddress, kind); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('getState').inc(1); - - const state = await indexer.getPrevState(blockHash, contractAddress, kind); - - return state && state.block.isComplete ? getResultState(state) : undefined; - }, - - getSyncStatus: async () => { - log('getSyncStatus'); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('getSyncStatus').inc(1); - - return indexer.getSyncStatus(); - }, - - latestBlock: async () => { - log('latestBlock'); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('latestBlock').inc(1); - - return indexer.getLatestBlock(); - } - } - }; -}; diff --git a/packages/mobymask-v2-watcher/src/schema.gql b/packages/mobymask-v2-watcher/src/schema.gql deleted file mode 100644 index da107f9c..00000000 --- a/packages/mobymask-v2-watcher/src/schema.gql +++ /dev/null @@ -1,117 +0,0 @@ -scalar BigInt - -scalar BigDecimal - -scalar Bytes - -type Block_height { - hash: Bytes - number: Int -} - -type Proof { - data: String! -} - -type ResultBoolean { - value: Boolean! - proof: Proof -} - -type ResultString { - value: String! - proof: Proof -} - -type ResultInt { - value: Int! - proof: Proof -} - -type ResultBigInt { - value: BigInt! - proof: Proof -} - -type _Block_ { - cid: String! - hash: String! - number: Int! - timestamp: Int! - parentHash: String! -} - -type _Transaction_ { - hash: String! - index: Int! - from: String! - to: String! -} - -type ResultEvent { - block: _Block_! - tx: _Transaction_! - contract: String! - eventIndex: Int! - event: Event! - proof: Proof -} - -union Event = DelegationTriggeredEvent | MemberStatusUpdatedEvent | OwnershipTransferredEvent | PhisherStatusUpdatedEvent - -type DelegationTriggeredEvent { - principal: String! - agent: String! -} - -type MemberStatusUpdatedEvent { - entity: String! - isMember: Boolean! -} - -type OwnershipTransferredEvent { - previousOwner: String! - newOwner: String! -} - -type PhisherStatusUpdatedEvent { - entity: String! - isPhisher: Boolean! -} - -type ResultState { - block: _Block_! - contractAddress: String! - cid: String! - kind: String! - data: String! -} - -type SyncStatus { - latestIndexedBlockHash: String! - latestIndexedBlockNumber: Int! - latestCanonicalBlockHash: String! - latestCanonicalBlockNumber: Int! -} - -type Query { - events(blockHash: String!, contractAddress: String!, name: String): [ResultEvent!] - eventsInRange(fromBlockNumber: Int!, toBlockNumber: Int!): [ResultEvent!] - multiNonce(blockHash: String!, contractAddress: String!, key0: String!, key1: BigInt!): ResultBigInt! - _owner(blockHash: String!, contractAddress: String!): ResultString! - isRevoked(blockHash: String!, contractAddress: String!, key0: String!): ResultBoolean! - isPhisher(blockHash: String!, contractAddress: String!, key0: String!): ResultBoolean! - isMember(blockHash: String!, contractAddress: String!, key0: String!): ResultBoolean! - getStateByCID(cid: String!): ResultState - getState(blockHash: String!, contractAddress: String!, kind: String): ResultState - getSyncStatus: SyncStatus - latestBlock: Block_height -} - -type Mutation { - watchContract(address: String!, kind: String!, checkpoint: Boolean!, startingBlock: Int): Boolean! -} - -type Subscription { - onEvent: ResultEvent! -} diff --git a/packages/mobymask-v2-watcher/src/server.ts b/packages/mobymask-v2-watcher/src/server.ts deleted file mode 100644 index f2baeccf..00000000 --- a/packages/mobymask-v2-watcher/src/server.ts +++ /dev/null @@ -1,43 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// - -import fs from 'fs'; -import path from 'path'; -import assert from 'assert'; -import 'reflect-metadata'; -import debug from 'debug'; -import { ethers } from 'ethers'; - -import { ServerCmd } from '@cerc-io/cli'; - -import { createResolvers } from './resolvers'; -import { Indexer } from './indexer'; -import { Database } from './database'; -import { createMessageToL2Handler, parseLibp2pMessage } from './libp2p-utils'; - -const log = debug('vulcanize:server'); - -export const main = async (): Promise => { - const serverCmd = new ServerCmd(); - await serverCmd.init(Database); - await serverCmd.initIndexer(Indexer); - - let p2pMessageHandler = parseLibp2pMessage; - const { enableL2Txs, l2TxsConfig } = serverCmd.config.server.p2p.peer; - - if (enableL2Txs) { - assert(l2TxsConfig); - const wallet = new ethers.Wallet(l2TxsConfig.privateKey, serverCmd.ethProvider); - p2pMessageHandler = createMessageToL2Handler(wallet, l2TxsConfig); - } - - const typeDefs = fs.readFileSync(path.join(__dirname, 'schema.gql')).toString(); - return serverCmd.exec(createResolvers, typeDefs, p2pMessageHandler); -}; - -main().then(() => { - log('Starting server...'); -}).catch(err => { - log(err); -}); diff --git a/packages/mobymask-v2-watcher/src/types.ts b/packages/mobymask-v2-watcher/src/types.ts deleted file mode 100644 index 7b4d6e02..00000000 --- a/packages/mobymask-v2-watcher/src/types.ts +++ /dev/null @@ -1,3 +0,0 @@ -// -// Copyright 2023 Vulcanize, Inc. -// diff --git a/packages/mobymask-v2-watcher/tsconfig.json b/packages/mobymask-v2-watcher/tsconfig.json deleted file mode 100644 index 5f2b3ad2..00000000 --- a/packages/mobymask-v2-watcher/tsconfig.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "compilerOptions": { - /* Visit https://aka.ms/tsconfig.json to read more about this file */ - - /* Basic Options */ - // "incremental": true, /* Enable incremental compilation */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ - "module": "CommonJS", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ - "lib": [ "ES5", "ES6", "ES2020" ], /* Specify library files to be included in the compilation. */ - // "allowJs": true, /* Allow javascript files to be compiled. */ - // "checkJs": true, /* Report errors in .js files. */ - // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ - // "declaration": true, /* Generates corresponding '.d.ts' file. */ - // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - "sourceMap": true, /* Generates corresponding '.map' file. */ - // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "dist", /* Redirect output structure to the directory. */ - // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - // "composite": true, /* Enable project compilation */ - // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ - // "removeComments": true, /* Do not emit comments to output. */ - // "noEmit": true, /* Do not emit outputs. */ - // "importHelpers": true, /* Import emit helpers from 'tslib'. */ - "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ - // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* Enable strict null checks. */ - // "strictFunctionTypes": true, /* Enable strict checking of function types. */ - // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ - // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ - // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - - /* Additional Checks */ - // "noUnusedLocals": true, /* Report errors on unused locals. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ - - /* Module Resolution Options */ - "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ - // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ - // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ - // "typeRoots": [], /* List of folders to include type definitions from. */ - // "types": [], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ - // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - - /* Source Map Options */ - // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ - // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - - /* Experimental Options */ - "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ - // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - - /* Advanced Options */ - "skipLibCheck": true, /* Skip type checking of declaration files. */ - "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ - "resolveJsonModule": true /* Enabling the option allows importing JSON, and validating the types in that JSON file. */ - }, - "include": ["src/**/*"] -} diff --git a/packages/mobymask-watcher/.eslintignore b/packages/mobymask-watcher/.eslintignore deleted file mode 100644 index 55cb5225..00000000 --- a/packages/mobymask-watcher/.eslintignore +++ /dev/null @@ -1,2 +0,0 @@ -# Don't lint build output. -dist diff --git a/packages/mobymask-watcher/.eslintrc.json b/packages/mobymask-watcher/.eslintrc.json deleted file mode 100644 index a2b842c2..00000000 --- a/packages/mobymask-watcher/.eslintrc.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "env": { - "browser": true, - "es2021": true - }, - "extends": [ - "semistandard", - "plugin:@typescript-eslint/recommended" - ], - "parser": "@typescript-eslint/parser", - "parserOptions": { - "ecmaVersion": 12, - "sourceType": "module" - }, - "plugins": [ - "@typescript-eslint" - ], - "rules": { - "indent": ["error", 2, { "SwitchCase": 1 }], - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/explicit-module-boundary-types": [ - "warn", - { - "allowArgumentsExplicitlyTypedAsAny": true - } - ] - } -} diff --git a/packages/mobymask-watcher/README.md b/packages/mobymask-watcher/README.md deleted file mode 100644 index 4a81b846..00000000 --- a/packages/mobymask-watcher/README.md +++ /dev/null @@ -1,281 +0,0 @@ -# MobyMask Watcher - -First try the [mobymask demo in stack orchestrator](https://github.com/cerc-io/stack-orchestrator/tree/main/app/data/stacks/mobymask) to quickly get started. Advanced users can see [here](/docs/README.md) for instructions on setting up a local environment by hand. - -## Setup - -Run the following command to install required packages: - -```bash -yarn && yarn build -``` - -If the watcher is "lazy", run the server: - -```bash -yarn server -``` - -GQL console: http://localhost:3010/graphql - -If the watcher is "active", run the job-runner: - -```bash -yarn job-runner -``` -then the server: - -```bash -yarn server -``` - -Next, clone the MobyMask repo and checkout this branch: - -```bash -git clone https://github.com/cerc-io/MobyMask && cd MobyMask -git checkout use-laconic-watcher-as-hosted-index -``` - -Install the packages: -```bash -yarn -``` - -Deploy the contract: -```bash -cd packages/hardhat - -yarn deploy -# deploying "PhisherRegistry" (tx: 0xaebeb2e883ece1f679304ec46f5dc61ca74f9e168427268a7dfa8802195b8de0)...: deployed at 0xMobyAddress with 2306221 gas -# $ hardhat run scripts/publish.js -# ✅ Published contracts to the subgraph package. -# Done in 14.28s. -``` - -Export the address of the deployed contract to a shell variable for later use: - -```bash -export MOBY_ADDRESS="0xMobyAddress" -``` - -Run the following GQL mutation in watcher GraphQL endpoint http://127.0.0.1:3010/graphql - -```graphql -mutation { - watchContract( - address: "MOBY_ADDRESS" - kind: "PhisherRegistry" - checkpoint: true - ) -} -``` - -Get the latest block - - ```graphql - query { - latestBlock { - hash - number - } - } - ``` - -Run the following GQL query in GraphQL endpoint - -```graphql -query { - isPhisher( - blockHash: "LATEST_BLOCK_HASH" - contractAddress: "MOBY_ADDRESS" - key0: "TWT:phishername" - ) { - value - proof { - data - } - } - isMember( - blockHash: "LATEST_BLOCK_HASH" - contractAddress: "MOBY_ADDRESS" - key0: "TWT:membername" - ) { - value - proof { - data - } - } -} -``` - -Run the following GQL subscription in generated watcher GraphQL endpoint: - -```graphql -subscription { - onEvent { - event { - __typename - ... on PhisherStatusUpdatedEvent { - entity - isPhisher - }, - ... on MemberStatusUpdatedEvent { - entity - isMember - } - }, - block { - number - hash - } - } -} -``` - -Update isPhiser and isMember lists with names - -```bash -yarn claimPhisher --contract $MOBY_ADDRESS --name phisherName -``` - -```bash -yarn claimMember --contract $MOBY_ADDRESS --name memberName -``` - -- The events should be visible in the subscription at GQL endpoint. Note down the event blockHash from result. - -- The isMember and isPhisher lists should be indexed. Check the database (mobymask-watcher) tables `is_phisher` and `is_member`, there should be entries at the event blockHash and the value should be true. The data is indexed in `handleEvent` method in the [hooks file](./src/hooks.ts). - -Update the the previous query with event blockHash and check isPhisher and isMember in GraphQL playground - -```graphql -query { - isPhisher( - blockHash: "EVENT_BLOCK_HASH" - contractAddress: "MOBY_ADDRESS", - key0: "TWT:phishername" - ) { - value - proof { - data - } - } - - isMember( - blockHash: "EVENT_BLOCK_HASH" - contractAddress: "MOBY_ADDRESS", - key0: "TWT:membername" - ) { - value - proof { - data - } - } -} -``` - -The data is fetched from watcher database as it is already indexed. - -## Additional Commands - -To watch a contract, run: - -```bash -yarn watch:contract --address --kind --checkpoint --starting-block [block-number] -``` -where: -- `address`: Address or identifier of the contract to be watched. -- `kind`: Kind of the contract. -- `checkpoint`: Turn checkpointing on (`true` | `false`). -- `starting-block`: Starting block for the contract (default: `1`). - -Examples: - -Watch a contract with its address and checkpointing on: - -```bash -yarn watch:contract --address 0x1F78641644feB8b64642e833cE4AFE93DD6e7833 --kind ERC20 --checkpoint true -``` - -Watch a contract with its identifier and checkpointing on: - -```bash -yarn watch:contract --address MyProtocol --kind protocol --checkpoint true -``` - -To fill a block range: - -```bash -yarn fill --start-block --end-block -``` - -* `start-block`: Block number to start filling from. -* `end-block`: Block number till which to fill. - -To create a checkpoint for a contract: - -```bash -yarn checkpoint create --address --block-hash [block-hash] -``` - -* `address`: Address or identifier of the contract for which to create a checkpoint. -* `block-hash`: Hash of a block (in the pruned region) at which to create the checkpoint (default: latest canonical block hash). - -To reset the watcher to a previous block number: - -```bash -yarn reset watcher --block-number -``` - -Reset job-queue: - -```bash -yarn reset job-queue -``` - -Reset state: - -```bash -yarn reset state --block-number -``` - -* `block-number`: Block number to which to reset the watcher. - -To export and import the watcher state: - -In the source watcher, export watcher state: - -```bash -yarn export-state --export-file [export-file-path] --block-number [snapshot-block-height] -``` - -* `export-file`: Path of file to which to export the watcher data. -* `block-number`: Block height at which to take snapshot for export. - -In the target watcher, run job-runner: - -```bash -yarn job-runner -``` - -Import watcher state: - -```bash -yarn import-state --import-file -``` - -* `import-file`: Path of file from which to import the watcher data. - -Run server: - -```bash -yarn server -``` - -To inspect a CID: - -```bash -yarn inspect-cid --cid -``` - -* `cid`: CID to be inspected. diff --git a/packages/mobymask-watcher/environments/local.toml b/packages/mobymask-watcher/environments/local.toml deleted file mode 100644 index 2c46f0f0..00000000 --- a/packages/mobymask-watcher/environments/local.toml +++ /dev/null @@ -1,55 +0,0 @@ -[server] - host = "127.0.0.1" - port = 3010 - kind = "active" - - # Checkpointing state. - checkpointing = true - - # Checkpoint interval in number of blocks. - checkpointInterval = 2000 - - # Enable state creation - enableState = true - - # Boolean to filter logs by contract. - filterLogs = true - - # Max block range for which to return events in eventsInRange GQL query. - # Use -1 for skipping check on block range. - maxEventsBlockRange = -1 - -[metrics] - host = "127.0.0.1" - port = 9000 - [metrics.gql] - port = 9001 - -[database] - type = "postgres" - host = "localhost" - port = 5432 - database = "mobymask-watcher" - username = "postgres" - password = "postgres" - synchronize = true - logging = false - -[upstream] - [upstream.ethServer] - gqlApiEndpoint = "http://127.0.0.1:8082/graphql" - rpcProviderEndpoint = "http://127.0.0.1:8081" - - [upstream.cache] - name = "requests" - enabled = false - deleteOnStart = false - -[jobQueue] - dbConnectionString = "postgres://postgres:postgres@localhost/mobymask-watcher-job-queue" - maxCompletionLagInSecs = 300 - jobDelayInMilliSecs = 100 - eventsInBatch = 50 - blockDelayInMilliSecs = 2000 - prefetchBlocksInMem = true - prefetchBlockCount = 10 diff --git a/packages/mobymask-watcher/indexing.md b/packages/mobymask-watcher/indexing.md deleted file mode 100644 index 2c8b21bd..00000000 --- a/packages/mobymask-watcher/indexing.md +++ /dev/null @@ -1,218 +0,0 @@ -# Index missing blocks with eth-statediff-service - -This readme can be followed to index required blocks out of order for a contract. This indexed data can then be used by the watcher further. - -* For indexing the required blocks the following core services will be used: - - * [ipld-eth-db](https://github.com/vulcanize/ipld-eth-db) - - * Run ipld-eth-db database using docker: - - ```bash - docker-compose -f docker-compose.yml up - ``` - - * [leveldb-ethdb-rpc](https://github.com/vulcanize/leveldb-ethdb-rpc) - - It is an RPC wrapper around LevelDB. The endpoint can be used by eth-statediff-service to access LevelDB. - - * [eth-statediff-service](https://github.com/vulcanize/eth-statediff-service) - - * The [config file](https://github.com/vulcanize/eth-statediff-service/blob/sharding/environments/config.toml) can be updated with the following for running eth-statediff-service: - - ```toml - [leveldb] - mode = "remote" - # leveldb-ethdb-rpc endpoint - url = "http://127.0.0.1:8082/" - - [server] - httpPath = "0.0.0.0:8545" - - [statediff] - prerun = false - serviceWorkers = 2 - workerQueueSize = 1024 - trieWorkers = 16 - - [log] - level = "info" - - [database] - # Credentials for ipld-eth-db database - name = "vulcanize_testing" - hostname = "localhost" - port = 8077 - user = "vdbm" - password = "password" - type = "postgres" - driver = "sqlx" - - [cache] - database = 1024 - trie = 4096 - - [ethereum] - # Config for mainnet - nodeID = "1" - clientName = "eth-statediff-service" - networkID = 1 - chainID = 1 - ``` - - * Run eth-statediff-service: - - ```bash - make build && ./eth-statediff-service serve --config environments/config.toml - ``` - -* Indexing required blocks can be done in the following way: - - * Call `writeStateDiffAt` API with watched addresses for required blocks: - - ```bash - # Replace $BLOCK_NUMBER with required block number to index and $CONTRACT_ADDRESS with the contract of interest. - curl -X POST -H 'Content-Type: application/json' --data '{"jsonrpc":"2.0","method":"statediff_writeStateDiffAt","params":[$BLOCK_NUMBER, {"intermediateStateNodes":true,"intermediateStorageNodes":true,"includeBlock":true,"includeReceipts":true,"includeTD":true,"includeCode":true,"watchedAddresses":["$CONTRACT_ADDRESS"]}],"id":1}' "127.0.0.1":"8545" - ``` - - Example for indexing [mainnet MobyMask blocks](https://etherscan.io/address/0xb06e6db9288324738f04fcaac910f5a60102c1f8): - - 14869713 - - 14875233 - - 14876405 - - 14884873 - - 14885755 - - ```bash - curl -X POST -H 'Content-Type: application/json' --data '{"jsonrpc":"2.0","method":"statediff_writeStateDiffAt","params":[14869713, {"intermediateStateNodes":true,"intermediateStorageNodes":true,"includeBlock":true,"includeReceipts":true,"includeTD":true,"includeCode":true,"watchedAddresses":["0xB06E6DB9288324738f04fCAAc910f5A60102C1F8"]}],"id":1}' "127.0.0.1":"8545" - ``` - - After successfully completing writeStateDiffAt for a block the returned response is: - - ```bash - curl: (52) Empty reply from server - ``` - - **NOTE**: Using remote leveldb-ethdb-rpc takes long time (6-20 minutes). - - * Stop the eth-statediff-service after all required blocks are indexed. - -* Start the [ipld-eth-server](https://github.com/vulcanize/eth-statediff-service) to query the indexed data from watcher. - - * Create the following config.toml file for ipld-eth-server in [environments directory](https://github.com/vulcanize/ipld-eth-server/tree/sharding/environments): - - ```toml - [database] - # Credentials for ipld-eth-db database - name = "vulcanize_testing" # $DATABASE_NAME - hostname = "localhost" # $DATABASE_HOSTNAME - port = 8077 # $DATABASE_PORT - user = "vdbm" # $DATABASE_USER - password = "password" # $DATABASE_PASSWORD - - [log] - level = "info" # $LOGRUS_LEVEL - - [ethereum] - # Config for mainnet - chainID = "1" # $ETH_CHAIN_ID - nodeID = "arch1" # $ETH_NODE_ID - clientName = "Geth" # $ETH_CLIENT_NAME - networkID = "1" # $ETH_NETWORK_ID - ``` - - * Run the server with the config above: - - ```bash - make build && ./ipld-eth-server serve --config=./environments/config.toml --eth-server-graphql --log-level info - ``` - -* The following steps are for indexing blocks out of order in the watcher: - - * Follow [steps in the readme](./README.md#setup) to setup the watcher. - - * Watch the contract: - - ```bash - # Replace $CONTRACT_ADDRESS and $CONTRACT_NAME witch actual values - yarn watch:contract --address $CONTRACT_ADDRESS --kind $CONTRACT_NAME --checkpoint true - - # Example for mobymask-watcher - yarn watch:contract --address 0xB06E6DB9288324738f04fCAAc910f5A60102C1F8 --kind PhisherRegistry --checkpoint true - ``` - - * Index the required blocks. They should be the same blocks indexed by eth-statediff-service above. - - ```bash - # Replace $BLOCK_NUMBER with required block number to index - yarn index-block --block $BLOCK_NUMBER - ``` - - Example for [mainnet MobyMask blocks](https://etherscan.io/address/0xb06e6db9288324738f04fcaac910f5a60102c1f8) indexed above: - ```bash - yarn index-block --block 14869713 - ``` - - * Check the `event` and `block_progress` table to confirm that the required blocks have been indexed properly. - -* The watcher can be started to perform queries on the indexed data: - - * The watcher can be started in lazy mode: - - * Update `server.kind` in [config](./environments/local.toml): - - ```toml - [server] - kind = "lazy" - ``` - - * Run server: - - ```bash - yarn server - ``` - - * Run query in [GraphQL endpoint](http://127.0.0.1:3010/graphql) to get events in a range. Following query is for getting events in the range of mainnet blocks indexed for mobymask-watcher: - - ```graphql - query { - eventsInRange( - # Range for mainnet data blocks - fromBlockNumber: 14869713 - toBlockNumber: 14885755 - ) { - block { - hash - number - } - tx { - hash - } - contract - eventIndex - event { - __typename - } - proof { - data - } - } - } - ``` - - * Run query to get contract storage variable values. The following query is for getting value of `isMember` variable in MobyMask contract: - - ```graphql - query { - isMember( - # BlockHash of an indexed mainnet block that can be taken from the events returned above - blockHash: "0x28cb16e740cd5d7de869bee2957e7442790e9d774e6e71804a67933c7e628038" - contractAddress: "0xB06E6DB9288324738f04fCAAc910f5A60102C1F8" - key0: "TWT:danfinlay" - ) { - value - proof { - data - } - } - } - ``` diff --git a/packages/mobymask-watcher/package.json b/packages/mobymask-watcher/package.json deleted file mode 100644 index e32bedc9..00000000 --- a/packages/mobymask-watcher/package.json +++ /dev/null @@ -1,71 +0,0 @@ -{ - "name": "@cerc-io/mobymask-watcher", - "version": "0.2.38", - "description": "mobymask-watcher", - "private": true, - "main": "dist/index.js", - "scripts": { - "lint": "eslint .", - "build": "yarn clean && tsc && yarn copy-assets", - "clean": "rm -rf ./dist", - "copy-assets": "copyfiles -u 1 src/**/*.gql dist/", - "server": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true node --enable-source-maps dist/server.js", - "server:dev": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true ts-node src/server.ts", - "job-runner": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true node --enable-source-maps dist/job-runner.js", - "job-runner:dev": "DEBUG=vulcanize:* YARN_CHILD_PROCESS=true ts-node src/job-runner.ts", - "watch:contract": "DEBUG=vulcanize:* ts-node src/cli/watch-contract.ts", - "fill": "DEBUG=vulcanize:* ts-node src/fill.ts", - "reset": "DEBUG=vulcanize:* ts-node src/cli/reset.ts", - "checkpoint": "DEBUG=vulcanize:* node --enable-source-maps dist/cli/checkpoint.js", - "checkpoint:dev": "DEBUG=vulcanize:* ts-node src/cli/checkpoint.ts", - "export-state": "DEBUG=vulcanize:* node --enable-source-maps dist/cli/export-state.js", - "export-state:dev": "DEBUG=vulcanize:* ts-node src/cli/export-state.ts", - "import-state": "DEBUG=vulcanize:* node --enable-source-maps dist/cli/import-state.js", - "import-state:dev": "DEBUG=vulcanize:* ts-node src/cli/import-state.ts", - "inspect-cid": "DEBUG=vulcanize:* ts-node src/cli/inspect-cid.ts", - "index-block": "DEBUG=vulcanize:* ts-node src/cli/index-block.ts" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/cerc-io/watcher-ts.git" - }, - "author": "", - "license": "AGPL-3.0", - "bugs": { - "url": "https://github.com/cerc-io/watcher-ts/issues" - }, - "homepage": "https://github.com/cerc-io/watcher-ts#readme", - "dependencies": { - "@apollo/client": "^3.3.19", - "@cerc-io/cli": "^0.2.38", - "@cerc-io/ipld-eth-client": "^0.2.38", - "@cerc-io/solidity-mapper": "^0.2.38", - "@cerc-io/util": "^0.2.38", - "@ethersproject/providers": "^5.4.4", - "apollo-type-bigint": "^0.1.3", - "debug": "^4.3.1", - "decimal.js": "^10.3.1", - "ethers": "^5.4.4", - "graphql": "^15.5.0", - "json-bigint": "^1.0.0", - "reflect-metadata": "^0.1.13", - "typeorm": "^0.2.32", - "yargs": "^17.0.1" - }, - "devDependencies": { - "@ethersproject/abi": "^5.3.0", - "@types/yargs": "^17.0.0", - "@typescript-eslint/eslint-plugin": "^5.47.1", - "@typescript-eslint/parser": "^5.47.1", - "copyfiles": "^2.4.1", - "eslint": "^8.35.0", - "eslint-config-semistandard": "^15.0.1", - "eslint-config-standard": "^16.0.3", - "eslint-plugin-import": "^2.27.5", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-promise": "^5.1.0", - "eslint-plugin-standard": "^5.0.0", - "ts-node": "^10.2.1", - "typescript": "^5.0.2" - } -} diff --git a/packages/mobymask-watcher/src/artifacts/PhisherRegistry.json b/packages/mobymask-watcher/src/artifacts/PhisherRegistry.json deleted file mode 100644 index 71bf3d46..00000000 --- a/packages/mobymask-watcher/src/artifacts/PhisherRegistry.json +++ /dev/null @@ -1,1934 +0,0 @@ -{ - "abi": [ - { - "inputs": [ - { - "internalType": "string", - "name": "name", - "type": "string" - } - ], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "address", - "name": "principal", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "agent", - "type": "address" - } - ], - "name": "DelegationTriggered", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "string", - "name": "entity", - "type": "string" - }, - { - "indexed": false, - "internalType": "bool", - "name": "isMember", - "type": "bool" - } - ], - "name": "MemberStatusUpdated", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "previousOwner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "newOwner", - "type": "address" - } - ], - "name": "OwnershipTransferred", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "string", - "name": "entity", - "type": "string" - }, - { - "indexed": false, - "internalType": "bool", - "name": "isPhisher", - "type": "bool" - } - ], - "name": "PhisherStatusUpdated", - "type": "event" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "_input", - "type": "tuple[]" - } - ], - "name": "GET_CAVEAT_ARRAY_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_CAVEAT_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_DELEGATION_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "string", - "name": "name", - "type": "string" - }, - { - "internalType": "string", - "name": "version", - "type": "string" - }, - { - "internalType": "uint256", - "name": "chainId", - "type": "uint256" - }, - { - "internalType": "address", - "name": "verifyingContract", - "type": "address" - } - ], - "internalType": "struct EIP712Domain", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_EIP712DOMAIN_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "bytes32", - "name": "delegationHash", - "type": "bytes32" - } - ], - "internalType": "struct IntentionToRevoke", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_INTENTIONTOREVOKE_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "authority", - "type": "tuple[]" - } - ], - "internalType": "struct Invocation[]", - "name": "batch", - "type": "tuple[]" - }, - { - "components": [ - { - "internalType": "uint256", - "name": "nonce", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "queue", - "type": "uint256" - } - ], - "internalType": "struct ReplayProtection", - "name": "replayProtection", - "type": "tuple" - } - ], - "internalType": "struct Invocations", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_INVOCATIONS_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "authority", - "type": "tuple[]" - } - ], - "internalType": "struct Invocation[]", - "name": "_input", - "type": "tuple[]" - } - ], - "name": "GET_INVOCATION_ARRAY_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "authority", - "type": "tuple[]" - } - ], - "internalType": "struct Invocation", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_INVOCATION_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "nonce", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "queue", - "type": "uint256" - } - ], - "internalType": "struct ReplayProtection", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_REPLAYPROTECTION_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "_input", - "type": "tuple[]" - } - ], - "name": "GET_SIGNEDDELEGATION_ARRAY_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_SIGNEDDELEGATION_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - }, - { - "components": [ - { - "internalType": "bytes32", - "name": "delegationHash", - "type": "bytes32" - } - ], - "internalType": "struct IntentionToRevoke", - "name": "intentionToRevoke", - "type": "tuple" - } - ], - "internalType": "struct SignedIntentionToRevoke", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_SIGNEDINTENTIONTOREVOKE_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "authority", - "type": "tuple[]" - } - ], - "internalType": "struct Invocation[]", - "name": "batch", - "type": "tuple[]" - }, - { - "components": [ - { - "internalType": "uint256", - "name": "nonce", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "queue", - "type": "uint256" - } - ], - "internalType": "struct ReplayProtection", - "name": "replayProtection", - "type": "tuple" - } - ], - "internalType": "struct Invocations", - "name": "invocations", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedInvocation", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_SIGNEDINVOCATION_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "_input", - "type": "tuple" - } - ], - "name": "GET_TRANSACTION_PACKETHASH", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "string", - "name": "identifier", - "type": "string" - }, - { - "internalType": "bool", - "name": "isNominated", - "type": "bool" - } - ], - "name": "claimIfMember", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "string", - "name": "identifier", - "type": "string" - }, - { - "internalType": "bool", - "name": "isAccused", - "type": "bool" - } - ], - "name": "claimIfPhisher", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "authority", - "type": "tuple[]" - } - ], - "internalType": "struct Invocation[]", - "name": "batch", - "type": "tuple[]" - } - ], - "name": "contractInvoke", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "domainHash", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - }, - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "internalType": "bytes32", - "name": "delegationHash", - "type": "bytes32" - } - ], - "name": "enforceCaveat", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - } - ], - "name": "getDelegationTypedDataHash", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "string", - "name": "contractName", - "type": "string" - }, - { - "internalType": "string", - "name": "version", - "type": "string" - }, - { - "internalType": "uint256", - "name": "chainId", - "type": "uint256" - }, - { - "internalType": "address", - "name": "verifyingContract", - "type": "address" - } - ], - "name": "getEIP712DomainHash", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "bytes32", - "name": "delegationHash", - "type": "bytes32" - } - ], - "internalType": "struct IntentionToRevoke", - "name": "intentionToRevoke", - "type": "tuple" - } - ], - "name": "getIntentionToRevokeTypedDataHash", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "authority", - "type": "tuple[]" - } - ], - "internalType": "struct Invocation[]", - "name": "batch", - "type": "tuple[]" - }, - { - "components": [ - { - "internalType": "uint256", - "name": "nonce", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "queue", - "type": "uint256" - } - ], - "internalType": "struct ReplayProtection", - "name": "replayProtection", - "type": "tuple" - } - ], - "internalType": "struct Invocations", - "name": "invocations", - "type": "tuple" - } - ], - "name": "getInvocationsTypedDataHash", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "authority", - "type": "tuple[]" - } - ], - "internalType": "struct Invocation[]", - "name": "batch", - "type": "tuple[]" - }, - { - "components": [ - { - "internalType": "uint256", - "name": "nonce", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "queue", - "type": "uint256" - } - ], - "internalType": "struct ReplayProtection", - "name": "replayProtection", - "type": "tuple" - } - ], - "internalType": "struct Invocations", - "name": "invocations", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedInvocation[]", - "name": "signedInvocations", - "type": "tuple[]" - } - ], - "name": "invoke", - "outputs": [ - { - "internalType": "bool", - "name": "success", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "name": "isMember", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "name": "isPhisher", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - }, - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "name": "multiNonce", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "owner", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "renounceOwnership", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation", - "name": "signedDelegation", - "type": "tuple" - }, - { - "components": [ - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - }, - { - "components": [ - { - "internalType": "bytes32", - "name": "delegationHash", - "type": "bytes32" - } - ], - "internalType": "struct IntentionToRevoke", - "name": "intentionToRevoke", - "type": "tuple" - } - ], - "internalType": "struct SignedIntentionToRevoke", - "name": "signedIntentionToRevoke", - "type": "tuple" - } - ], - "name": "revokeDelegation", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "newOwner", - "type": "address" - } - ], - "name": "transferOwnership", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation", - "name": "signedDelegation", - "type": "tuple" - } - ], - "name": "verifyDelegationSignature", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - }, - { - "components": [ - { - "internalType": "bytes32", - "name": "delegationHash", - "type": "bytes32" - } - ], - "internalType": "struct IntentionToRevoke", - "name": "intentionToRevoke", - "type": "tuple" - } - ], - "internalType": "struct SignedIntentionToRevoke", - "name": "signedIntentionToRevoke", - "type": "tuple" - } - ], - "name": "verifyIntentionToRevokeSignature", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "components": [ - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "gasLimit", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "internalType": "struct Transaction", - "name": "transaction", - "type": "tuple" - }, - { - "components": [ - { - "components": [ - { - "internalType": "address", - "name": "delegate", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "authority", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "address", - "name": "enforcer", - "type": "address" - }, - { - "internalType": "bytes", - "name": "terms", - "type": "bytes" - } - ], - "internalType": "struct Caveat[]", - "name": "caveats", - "type": "tuple[]" - } - ], - "internalType": "struct Delegation", - "name": "delegation", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedDelegation[]", - "name": "authority", - "type": "tuple[]" - } - ], - "internalType": "struct Invocation[]", - "name": "batch", - "type": "tuple[]" - }, - { - "components": [ - { - "internalType": "uint256", - "name": "nonce", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "queue", - "type": "uint256" - } - ], - "internalType": "struct ReplayProtection", - "name": "replayProtection", - "type": "tuple" - } - ], - "internalType": "struct Invocations", - "name": "invocations", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "signature", - "type": "bytes" - } - ], - "internalType": "struct SignedInvocation", - "name": "signedInvocation", - "type": "tuple" - } - ], - "name": "verifyInvocationSignature", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - } - ], - "storageLayout": { - "storage": [ - { - "astId": 1238, - "contract": "PhisherRegistry.sol:PhisherRegistry", - "label": "_owner", - "offset": 0, - "slot": "0", - "type": "t_address" - }, - { - "astId": 969, - "contract": "PhisherRegistry.sol:PhisherRegistry", - "label": "multiNonce", - "offset": 0, - "slot": "1", - "type": "t_mapping(t_address,t_mapping(t_uint256,t_uint256))" - }, - { - "astId": 1354, - "contract": "PhisherRegistry.sol:PhisherRegistry", - "label": "isRevoked", - "offset": 0, - "slot": "2", - "type": "t_mapping(t_bytes32,t_bool)" - }, - { - "astId": 1554, - "contract": "PhisherRegistry.sol:PhisherRegistry", - "label": "isPhisher", - "offset": 0, - "slot": "3", - "type": "t_mapping(t_string_memory_ptr,t_bool)" - }, - { - "astId": 1585, - "contract": "PhisherRegistry.sol:PhisherRegistry", - "label": "isMember", - "offset": 0, - "slot": "4", - "type": "t_mapping(t_string_memory_ptr,t_bool)" - } - ], - "types": { - "t_address": { - "encoding": "inplace", - "label": "address", - "numberOfBytes": "20" - }, - "t_bool": { - "encoding": "inplace", - "label": "bool", - "numberOfBytes": "1" - }, - "t_bytes32": { - "encoding": "inplace", - "label": "bytes32", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_mapping(t_uint256,t_uint256))": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => mapping(uint256 => uint256))", - "numberOfBytes": "32", - "value": "t_mapping(t_uint256,t_uint256)" - }, - "t_mapping(t_bytes32,t_bool)": { - "encoding": "mapping", - "key": "t_bytes32", - "label": "mapping(bytes32 => bool)", - "numberOfBytes": "32", - "value": "t_bool" - }, - "t_mapping(t_string_memory_ptr,t_bool)": { - "encoding": "mapping", - "key": "t_string_memory_ptr", - "label": "mapping(string => bool)", - "numberOfBytes": "32", - "value": "t_bool" - }, - "t_mapping(t_uint256,t_uint256)": { - "encoding": "mapping", - "key": "t_uint256", - "label": "mapping(uint256 => uint256)", - "numberOfBytes": "32", - "value": "t_uint256" - }, - "t_string_memory_ptr": { - "encoding": "bytes", - "label": "string", - "numberOfBytes": "32" - }, - "t_uint256": { - "encoding": "inplace", - "label": "uint256", - "numberOfBytes": "32" - } - } - } -} \ No newline at end of file diff --git a/packages/mobymask-watcher/src/cli/checkpoint-cmds/create.ts b/packages/mobymask-watcher/src/cli/checkpoint-cmds/create.ts deleted file mode 100644 index 01408fe5..00000000 --- a/packages/mobymask-watcher/src/cli/checkpoint-cmds/create.ts +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { CreateCheckpointCmd } from '@cerc-io/cli'; - -import { Database } from '../../database'; -import { Indexer } from '../../indexer'; - -export const command = 'create'; - -export const desc = 'Create checkpoint'; - -export const builder = { - address: { - type: 'string', - require: true, - demandOption: true, - describe: 'Contract address to create the checkpoint for.' - }, - blockHash: { - type: 'string', - describe: 'Blockhash at which to create the checkpoint.' - } -}; - -export const handler = async (argv: any): Promise => { - const createCheckpointCmd = new CreateCheckpointCmd(); - await createCheckpointCmd.init(argv, Database); - await createCheckpointCmd.initIndexer(Indexer); - - await createCheckpointCmd.exec(); -}; diff --git a/packages/mobymask-watcher/src/cli/checkpoint.ts b/packages/mobymask-watcher/src/cli/checkpoint.ts deleted file mode 100644 index d05ad8ad..00000000 --- a/packages/mobymask-watcher/src/cli/checkpoint.ts +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import yargs from 'yargs'; -import 'reflect-metadata'; -import debug from 'debug'; - -import { DEFAULT_CONFIG_PATH } from '@cerc-io/util'; - -import { hideBin } from 'yargs/helpers'; - -const log = debug('vulcanize:checkpoint'); - -const main = async () => { - return yargs(hideBin(process.argv)) - .parserConfiguration({ - 'parse-numbers': false - }).options({ - configFile: { - alias: 'f', - type: 'string', - require: true, - demandOption: true, - describe: 'configuration file path (toml)', - default: DEFAULT_CONFIG_PATH - } - }) - .commandDir('checkpoint-cmds', { extensions: ['ts', 'js'], exclude: /([a-zA-Z0-9\s_\\.\-:])+(.d.ts)$/ }) - .demandCommand(1) - .help() - .argv; -}; - -main().then(() => { - process.exit(); -}).catch(err => { - log(err); -}); diff --git a/packages/mobymask-watcher/src/cli/export-state.ts b/packages/mobymask-watcher/src/cli/export-state.ts deleted file mode 100644 index d0ae922d..00000000 --- a/packages/mobymask-watcher/src/cli/export-state.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { ExportStateCmd } from '@cerc-io/cli'; - -import { Database } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:export-state'); - -const main = async (): Promise => { - const exportStateCmd = new ExportStateCmd(); - await exportStateCmd.init(Database); - await exportStateCmd.initIndexer(Indexer); - - await exportStateCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/mobymask-watcher/src/cli/import-state.ts b/packages/mobymask-watcher/src/cli/import-state.ts deleted file mode 100644 index 79771fcd..00000000 --- a/packages/mobymask-watcher/src/cli/import-state.ts +++ /dev/null @@ -1,28 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { ImportStateCmd } from '@cerc-io/cli'; - -import { Database } from '../database'; -import { Indexer } from '../indexer'; -import { State } from '../entity/State'; - -const log = debug('vulcanize:import-state'); - -export const main = async (): Promise => { - const importStateCmd = new ImportStateCmd(); - await importStateCmd.init(Database); - await importStateCmd.initIndexer(Indexer); - - await importStateCmd.exec(State); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/mobymask-watcher/src/cli/index-block.ts b/packages/mobymask-watcher/src/cli/index-block.ts deleted file mode 100644 index 4ebad2a0..00000000 --- a/packages/mobymask-watcher/src/cli/index-block.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { IndexBlockCmd } from '@cerc-io/cli'; - -import { Database } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:index-block'); - -const main = async (): Promise => { - const indexBlockCmd = new IndexBlockCmd(); - await indexBlockCmd.init(Database); - await indexBlockCmd.initIndexer(Indexer); - - await indexBlockCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/mobymask-watcher/src/cli/inspect-cid.ts b/packages/mobymask-watcher/src/cli/inspect-cid.ts deleted file mode 100644 index 740cfdf3..00000000 --- a/packages/mobymask-watcher/src/cli/inspect-cid.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { InspectCIDCmd } from '@cerc-io/cli'; - -import { Database } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:inspect-cid'); - -const main = async (): Promise => { - const inspectCIDCmd = new InspectCIDCmd(); - await inspectCIDCmd.init(Database); - await inspectCIDCmd.initIndexer(Indexer); - - await inspectCIDCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/mobymask-watcher/src/cli/reset-cmds/job-queue.ts b/packages/mobymask-watcher/src/cli/reset-cmds/job-queue.ts deleted file mode 100644 index c33cbfd6..00000000 --- a/packages/mobymask-watcher/src/cli/reset-cmds/job-queue.ts +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import debug from 'debug'; - -import { getConfig, resetJobs, Config } from '@cerc-io/util'; - -const log = debug('vulcanize:reset-job-queue'); - -export const command = 'job-queue'; - -export const desc = 'Reset job queue'; - -export const builder = {}; - -export const handler = async (argv: any): Promise => { - const config: Config = await getConfig(argv.configFile); - await resetJobs(config); - - log('Job queue reset successfully'); -}; diff --git a/packages/mobymask-watcher/src/cli/reset-cmds/state.ts b/packages/mobymask-watcher/src/cli/reset-cmds/state.ts deleted file mode 100644 index 33211d6e..00000000 --- a/packages/mobymask-watcher/src/cli/reset-cmds/state.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2022 Vulcanize, Inc. -// - -import { ResetStateCmd } from '@cerc-io/cli'; - -import { Database } from '../../database'; - -export const command = 'state'; - -export const desc = 'Reset State to a given block number'; - -export const builder = { - blockNumber: { - type: 'number' - } -}; - -export const handler = async (argv: any): Promise => { - const resetStateCmd = new ResetStateCmd(); - await resetStateCmd.init(argv, Database); - - await resetStateCmd.exec(); -}; diff --git a/packages/mobymask-watcher/src/cli/reset-cmds/watcher.ts b/packages/mobymask-watcher/src/cli/reset-cmds/watcher.ts deleted file mode 100644 index c6e651f5..00000000 --- a/packages/mobymask-watcher/src/cli/reset-cmds/watcher.ts +++ /dev/null @@ -1,26 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { ResetWatcherCmd } from '@cerc-io/cli'; - -import { Database } from '../../database'; -import { Indexer } from '../../indexer'; - -export const command = 'watcher'; - -export const desc = 'Reset watcher to a block number'; - -export const builder = { - blockNumber: { - type: 'number' - } -}; - -export const handler = async (argv: any): Promise => { - const resetWatcherCmd = new ResetWatcherCmd(); - await resetWatcherCmd.init(argv, Database); - await resetWatcherCmd.initIndexer(Indexer); - - await resetWatcherCmd.exec(); -}; diff --git a/packages/mobymask-watcher/src/cli/reset.ts b/packages/mobymask-watcher/src/cli/reset.ts deleted file mode 100644 index 95648c88..00000000 --- a/packages/mobymask-watcher/src/cli/reset.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { getResetYargs } from '@cerc-io/util'; - -const log = debug('vulcanize:reset'); - -const main = async () => { - return getResetYargs() - .commandDir('reset-cmds', { extensions: ['ts', 'js'], exclude: /([a-zA-Z0-9\s_\\.\-:])+(.d.ts)$/ }) - .demandCommand(1) - .help() - .argv; -}; - -main().then(() => { - process.exit(); -}).catch(err => { - log(err); -}); diff --git a/packages/mobymask-watcher/src/cli/watch-contract.ts b/packages/mobymask-watcher/src/cli/watch-contract.ts deleted file mode 100644 index b68568e7..00000000 --- a/packages/mobymask-watcher/src/cli/watch-contract.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { WatchContractCmd } from '@cerc-io/cli'; - -import { Database } from '../database'; -import { Indexer } from '../indexer'; - -const log = debug('vulcanize:watch-contract'); - -const main = async (): Promise => { - const watchContractCmd = new WatchContractCmd(); - await watchContractCmd.init(Database); - await watchContractCmd.initIndexer(Indexer); - - await watchContractCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(0); -}); diff --git a/packages/mobymask-watcher/src/client.ts b/packages/mobymask-watcher/src/client.ts deleted file mode 100644 index 7f9555af..00000000 --- a/packages/mobymask-watcher/src/client.ts +++ /dev/null @@ -1,100 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { gql } from '@apollo/client/core'; -import { GraphQLClient, GraphQLConfig } from '@cerc-io/ipld-eth-client'; - -import { queries, mutations, subscriptions } from './gql'; - -export class Client { - _config: GraphQLConfig; - _client: GraphQLClient; - - constructor (config: GraphQLConfig) { - this._config = config; - - this._client = new GraphQLClient(config); - } - - async getMultiNonce (blockHash: string, contractAddress: string, key0: string, key1: bigint): Promise { - const { multiNonce } = await this._client.query( - gql(queries.multiNonce), - { blockHash, contractAddress, key0, key1 } - ); - - return multiNonce; - } - - async _getOwner (blockHash: string, contractAddress: string): Promise { - const { _owner } = await this._client.query( - gql(queries._owner), - { blockHash, contractAddress } - ); - - return _owner; - } - - async getIsRevoked (blockHash: string, contractAddress: string, key0: string): Promise { - const { isRevoked } = await this._client.query( - gql(queries.isRevoked), - { blockHash, contractAddress, key0 } - ); - - return isRevoked; - } - - async getIsPhisher (blockHash: string, contractAddress: string, key0: string): Promise { - const { isPhisher } = await this._client.query( - gql(queries.isPhisher), - { blockHash, contractAddress, key0 } - ); - - return isPhisher; - } - - async getIsMember (blockHash: string, contractAddress: string, key0: string): Promise { - const { isMember } = await this._client.query( - gql(queries.isMember), - { blockHash, contractAddress, key0 } - ); - - return isMember; - } - - async getEvents (blockHash: string, contractAddress: string, name: string): Promise { - const { events } = await this._client.query( - gql(queries.events), - { blockHash, contractAddress, name } - ); - - return events; - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise { - const { eventsInRange } = await this._client.query( - gql(queries.eventsInRange), - { fromBlockNumber, toBlockNumber } - ); - - return eventsInRange; - } - - async watchContract (contractAddress: string, startingBlock?: number): Promise { - const { watchContract } = await this._client.mutate( - gql(mutations.watchContract), - { contractAddress, startingBlock } - ); - - return watchContract; - } - - async watchEvents (onNext: (value: any) => void): Promise { - return this._client.subscribe( - gql(subscriptions.onEvent), - ({ data }) => { - onNext(data.onEvent); - } - ); - } -} diff --git a/packages/mobymask-watcher/src/database.ts b/packages/mobymask-watcher/src/database.ts deleted file mode 100644 index 03873bb8..00000000 --- a/packages/mobymask-watcher/src/database.ts +++ /dev/null @@ -1,352 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import { Connection, ConnectionOptions, DeepPartial, FindConditions, QueryRunner, FindManyOptions, LessThanOrEqual, EntityTarget } from 'typeorm'; -import path from 'path'; - -import { Database as BaseDatabase, DatabaseInterface, QueryOptions, StateKind, Where } from '@cerc-io/util'; - -import { Contract } from './entity/Contract'; -import { Event } from './entity/Event'; -import { SyncStatus } from './entity/SyncStatus'; -import { StateSyncStatus } from './entity/StateSyncStatus'; -import { BlockProgress } from './entity/BlockProgress'; -import { State } from './entity/State'; -import { MultiNonce } from './entity/MultiNonce'; -import { _Owner } from './entity/_Owner'; -import { IsRevoked } from './entity/IsRevoked'; -import { IsPhisher } from './entity/IsPhisher'; -import { IsMember } from './entity/IsMember'; - -export const ENTITIES = [_Owner, IsMember, IsPhisher, IsRevoked, MultiNonce]; - -export class Database implements DatabaseInterface { - _config: ConnectionOptions; - _conn!: Connection; - _baseDatabase: BaseDatabase; - _propColMaps: { [key: string]: Map; }; - - constructor (config: ConnectionOptions) { - assert(config); - - this._config = { - ...config, - entities: [path.join(__dirname, 'entity/*')] - }; - - this._baseDatabase = new BaseDatabase(this._config); - this._propColMaps = {}; - } - - get baseDatabase (): BaseDatabase { - return this._baseDatabase; - } - - async init (): Promise { - this._conn = await this._baseDatabase.init(); - this._setPropColMaps(); - } - - async close (): Promise { - return this._baseDatabase.close(); - } - - async getMultiNonce ({ blockHash, contractAddress, key0, key1 }: { blockHash: string, contractAddress: string, key0: string, key1: bigint }): Promise { - return this._conn.getRepository(MultiNonce) - .findOne({ - blockHash, - contractAddress, - key0, - key1 - }); - } - - async _getOwner ({ blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise<_Owner | undefined> { - return this._conn.getRepository(_Owner) - .findOne({ - blockHash, - contractAddress - }); - } - - async getIsRevoked ({ blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: string }): Promise { - return this._conn.getRepository(IsRevoked) - .findOne({ - blockHash, - contractAddress, - key0 - }); - } - - async getIsPhisher ({ blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: string }): Promise { - return this._conn.getRepository(IsPhisher) - .findOne({ - blockHash, - contractAddress, - key0 - }); - } - - async getIsMember ({ blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: string }): Promise { - return this._conn.getRepository(IsMember) - .findOne({ - blockHash, - contractAddress, - key0 - }); - } - - async getPrevEntity (entity: new () => Entity, fields: { blockNumber: number } & DeepPartial): Promise { - return this._conn.getRepository(entity) - .findOne({ - where: { - ...fields, - blockNumber: LessThanOrEqual(fields.blockNumber) - } - }); - } - - async saveMultiNonce ({ blockHash, blockNumber, contractAddress, key0, key1, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(MultiNonce); - const entity = repo.create({ blockHash, blockNumber, contractAddress, key0, key1, value, proof }); - return repo.save(entity); - } - - async _saveOwner ({ blockHash, blockNumber, contractAddress, value, proof }: DeepPartial<_Owner>): Promise<_Owner> { - const repo = this._conn.getRepository(_Owner); - const entity = repo.create({ blockHash, blockNumber, contractAddress, value, proof }); - return repo.save(entity); - } - - async saveIsRevoked ({ blockHash, blockNumber, contractAddress, key0, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(IsRevoked); - const entity = repo.create({ blockHash, blockNumber, contractAddress, key0, value, proof }); - return repo.save(entity); - } - - async saveIsPhisher ({ blockHash, blockNumber, contractAddress, key0, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(IsPhisher); - const entity = repo.create({ blockHash, blockNumber, contractAddress, key0, value, proof }); - return repo.save(entity); - } - - async saveIsMember ({ blockHash, blockNumber, contractAddress, key0, value, proof }: DeepPartial): Promise { - const repo = this._conn.getRepository(IsMember); - const entity = repo.create({ blockHash, blockNumber, contractAddress, key0, value, proof }); - return repo.save(entity); - } - - getNewState (): State { - return new State(); - } - - async getStates (where: FindConditions): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getStates(repo, where); - } - - async getLatestState (contractAddress: string, kind: StateKind | null, blockNumber?: number): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getLatestState(repo, contractAddress, kind, blockNumber); - } - - async getPrevState (blockHash: string, contractAddress: string, kind?: string): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getPrevState(repo, blockHash, contractAddress, kind); - } - - // Fetch all diff States after the specified block number. - async getDiffStatesInRange (contractAddress: string, startblock: number, endBlock: number): Promise { - const repo = this._conn.getRepository(State); - - return this._baseDatabase.getDiffStatesInRange(repo, contractAddress, startblock, endBlock); - } - - async saveOrUpdateState (dbTx: QueryRunner, state: State): Promise { - const repo = dbTx.manager.getRepository(State); - - return this._baseDatabase.saveOrUpdateState(repo, state); - } - - async removeStates (dbTx: QueryRunner, blockNumber: number, kind: string): Promise { - const repo = dbTx.manager.getRepository(State); - - await this._baseDatabase.removeStates(repo, blockNumber, kind); - } - - async removeStatesAfterBlock (dbTx: QueryRunner, blockNumber: number): Promise { - const repo = dbTx.manager.getRepository(State); - - await this._baseDatabase.removeStatesAfterBlock(repo, blockNumber); - } - - async getStateSyncStatus (): Promise { - const repo = this._conn.getRepository(StateSyncStatus); - - return this._baseDatabase.getStateSyncStatus(repo); - } - - async updateStateSyncStatusIndexedBlock (queryRunner: QueryRunner, blockNumber: number, force?: boolean): Promise { - const repo = queryRunner.manager.getRepository(StateSyncStatus); - - return this._baseDatabase.updateStateSyncStatusIndexedBlock(repo, blockNumber, force); - } - - async updateStateSyncStatusCheckpointBlock (queryRunner: QueryRunner, blockNumber: number, force?: boolean): Promise { - const repo = queryRunner.manager.getRepository(StateSyncStatus); - - return this._baseDatabase.updateStateSyncStatusCheckpointBlock(repo, blockNumber, force); - } - - async getContracts (): Promise { - const repo = this._conn.getRepository(Contract); - - return this._baseDatabase.getContracts(repo); - } - - async createTransactionRunner (): Promise { - return this._baseDatabase.createTransactionRunner(); - } - - async getProcessedBlockCountForRange (fromBlockNumber: number, toBlockNumber: number): Promise<{ expected: number, actual: number }> { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getProcessedBlockCountForRange(repo, fromBlockNumber, toBlockNumber); - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise> { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getEventsInRange(repo, fromBlockNumber, toBlockNumber); - } - - async saveEventEntity (queryRunner: QueryRunner, entity: Event): Promise { - const repo = queryRunner.manager.getRepository(Event); - return this._baseDatabase.saveEventEntity(repo, entity); - } - - async getBlockEvents (blockHash: string, where: Where, queryOptions: QueryOptions): Promise { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getBlockEvents(repo, blockHash, where, queryOptions); - } - - async saveBlockWithEvents (queryRunner: QueryRunner, block: DeepPartial, events: DeepPartial[]): Promise { - const blockRepo = queryRunner.manager.getRepository(BlockProgress); - const eventRepo = queryRunner.manager.getRepository(Event); - - return this._baseDatabase.saveBlockWithEvents(blockRepo, eventRepo, block, events); - } - - async saveEvents (queryRunner: QueryRunner, events: Event[]): Promise { - const eventRepo = queryRunner.manager.getRepository(Event); - - return this._baseDatabase.saveEvents(eventRepo, events); - } - - async saveBlockProgress (queryRunner: QueryRunner, block: DeepPartial): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.saveBlockProgress(repo, block); - } - - async saveContract (queryRunner: QueryRunner, address: string, kind: string, checkpoint: boolean, startingBlock: number): Promise { - const repo = queryRunner.manager.getRepository(Contract); - - return this._baseDatabase.saveContract(repo, address, kind, checkpoint, startingBlock); - } - - async updateSyncStatusIndexedBlock (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusIndexedBlock(repo, blockHash, blockNumber, force); - } - - async updateSyncStatusCanonicalBlock (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusCanonicalBlock(repo, blockHash, blockNumber, force); - } - - async updateSyncStatusChainHead (queryRunner: QueryRunner, blockHash: string, blockNumber: number, force = false): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.updateSyncStatusChainHead(repo, blockHash, blockNumber, force); - } - - async getSyncStatus (queryRunner: QueryRunner): Promise { - const repo = queryRunner.manager.getRepository(SyncStatus); - - return this._baseDatabase.getSyncStatus(repo); - } - - async getEvent (id: string): Promise { - const repo = this._conn.getRepository(Event); - - return this._baseDatabase.getEvent(repo, id); - } - - async getBlocksAtHeight (height: number, isPruned: boolean): Promise { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getBlocksAtHeight(repo, height, isPruned); - } - - async markBlocksAsPruned (queryRunner: QueryRunner, blocks: BlockProgress[]): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.markBlocksAsPruned(repo, blocks); - } - - async getBlockProgress (blockHash: string): Promise { - const repo = this._conn.getRepository(BlockProgress); - return this._baseDatabase.getBlockProgress(repo, blockHash); - } - - async getBlockProgressEntities (where: FindConditions, options: FindManyOptions): Promise { - const repo = this._conn.getRepository(BlockProgress); - - return this._baseDatabase.getBlockProgressEntities(repo, where, options); - } - - async getEntitiesForBlock (blockHash: string, tableName: string): Promise { - return this._baseDatabase.getEntitiesForBlock(blockHash, tableName); - } - - async updateBlockProgress (queryRunner: QueryRunner, block: BlockProgress, lastProcessedEventIndex: number): Promise { - const repo = queryRunner.manager.getRepository(BlockProgress); - - return this._baseDatabase.updateBlockProgress(repo, block, lastProcessedEventIndex); - } - - async removeEntities (queryRunner: QueryRunner, entity: new () => Entity, findConditions?: FindManyOptions | FindConditions): Promise { - return this._baseDatabase.removeEntities(queryRunner, entity, findConditions); - } - - async deleteEntitiesByConditions (queryRunner: QueryRunner, entity: EntityTarget, findConditions: FindConditions): Promise { - await this._baseDatabase.deleteEntitiesByConditions(queryRunner, entity, findConditions); - } - - async getAncestorAtDepth (blockHash: string, depth: number): Promise { - return this._baseDatabase.getAncestorAtDepth(blockHash, depth); - } - - _getPropertyColumnMapForEntity (entityName: string): Map { - return this._conn.getMetadata(entityName).ownColumns.reduce((acc, curr) => { - return acc.set(curr.propertyName, curr.databaseName); - }, new Map()); - } - - _setPropColMaps (): void { - this._propColMaps.MultiNonce = this._getPropertyColumnMapForEntity('MultiNonce'); - this._propColMaps._Owner = this._getPropertyColumnMapForEntity('_Owner'); - this._propColMaps.IsRevoked = this._getPropertyColumnMapForEntity('IsRevoked'); - this._propColMaps.IsPhisher = this._getPropertyColumnMapForEntity('IsPhisher'); - this._propColMaps.IsMember = this._getPropertyColumnMapForEntity('IsMember'); - } -} diff --git a/packages/mobymask-watcher/src/entity/BlockProgress.ts b/packages/mobymask-watcher/src/entity/BlockProgress.ts deleted file mode 100644 index e744aae4..00000000 --- a/packages/mobymask-watcher/src/entity/BlockProgress.ts +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, CreateDateColumn } from 'typeorm'; -import { BlockProgressInterface } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash'], { unique: true }) -@Index(['blockNumber']) -@Index(['parentHash']) -export class BlockProgress implements BlockProgressInterface { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar') - cid!: string; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('varchar', { length: 66 }) - parentHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('integer') - blockTimestamp!: number; - - @Column('integer') - numEvents!: number; - - @Column('integer') - numProcessedEvents!: number; - - @Column('integer') - lastProcessedEventIndex!: number; - - @Column('boolean') - isComplete!: boolean; - - @Column('boolean', { default: false }) - isPruned!: boolean; - - @CreateDateColumn() - createdAt!: Date; -} diff --git a/packages/mobymask-watcher/src/entity/Contract.ts b/packages/mobymask-watcher/src/entity/Contract.ts deleted file mode 100644 index de66b387..00000000 --- a/packages/mobymask-watcher/src/entity/Contract.ts +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['address'], { unique: true }) -export class Contract { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 42 }) - address!: string; - - @Column('varchar') - kind!: string; - - @Column('boolean') - checkpoint!: boolean; - - @Column('integer') - startingBlock!: number; -} diff --git a/packages/mobymask-watcher/src/entity/Event.ts b/packages/mobymask-watcher/src/entity/Event.ts deleted file mode 100644 index 91f1e6d3..00000000 --- a/packages/mobymask-watcher/src/entity/Event.ts +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, ManyToOne } from 'typeorm'; -import { BlockProgress } from './BlockProgress'; - -@Entity() -@Index(['block', 'contract']) -@Index(['block', 'contract', 'eventName']) -export class Event { - @PrimaryGeneratedColumn() - id!: number; - - @ManyToOne(() => BlockProgress, { onDelete: 'CASCADE' }) - block!: BlockProgress; - - @Column('varchar', { length: 66 }) - txHash!: string; - - @Column('integer') - index!: number; - - @Column('varchar', { length: 42 }) - contract!: string; - - @Column('varchar', { length: 256 }) - eventName!: string; - - @Column('text') - eventInfo!: string; - - @Column('text') - extraInfo!: string; - - @Column('text') - proof!: string; -} diff --git a/packages/mobymask-watcher/src/entity/IsMember.ts b/packages/mobymask-watcher/src/entity/IsMember.ts deleted file mode 100644 index 3d5a3824..00000000 --- a/packages/mobymask-watcher/src/entity/IsMember.ts +++ /dev/null @@ -1,30 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'key0'], { unique: true }) -export class IsMember { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - key0!: string; - - @Column('boolean') - value!: boolean; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/mobymask-watcher/src/entity/IsPhisher.ts b/packages/mobymask-watcher/src/entity/IsPhisher.ts deleted file mode 100644 index 92e8fd87..00000000 --- a/packages/mobymask-watcher/src/entity/IsPhisher.ts +++ /dev/null @@ -1,30 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'key0'], { unique: true }) -export class IsPhisher { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - key0!: string; - - @Column('boolean') - value!: boolean; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/mobymask-watcher/src/entity/IsRevoked.ts b/packages/mobymask-watcher/src/entity/IsRevoked.ts deleted file mode 100644 index 3c456ce9..00000000 --- a/packages/mobymask-watcher/src/entity/IsRevoked.ts +++ /dev/null @@ -1,30 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'key0'], { unique: true }) -export class IsRevoked { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - key0!: string; - - @Column('boolean') - value!: boolean; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/mobymask-watcher/src/entity/MultiNonce.ts b/packages/mobymask-watcher/src/entity/MultiNonce.ts deleted file mode 100644 index d33bf889..00000000 --- a/packages/mobymask-watcher/src/entity/MultiNonce.ts +++ /dev/null @@ -1,34 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; -import { bigintTransformer } from '@cerc-io/util'; - -@Entity() -@Index(['blockHash', 'contractAddress', 'key0', 'key1'], { unique: true }) -export class MultiNonce { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar', { length: 42 }) - key0!: string; - - @Column('numeric', { transformer: bigintTransformer }) - key1!: bigint; - - @Column('numeric', { transformer: bigintTransformer }) - value!: bigint; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/mobymask-watcher/src/entity/State.ts b/packages/mobymask-watcher/src/entity/State.ts deleted file mode 100644 index 10ef261e..00000000 --- a/packages/mobymask-watcher/src/entity/State.ts +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index, ManyToOne } from 'typeorm'; - -import { StateKind } from '@cerc-io/util'; - -import { BlockProgress } from './BlockProgress'; - -@Entity() -@Index(['cid'], { unique: true }) -@Index(['block', 'contractAddress']) -@Index(['block', 'contractAddress', 'kind'], { unique: true }) -export class State { - @PrimaryGeneratedColumn() - id!: number; - - @ManyToOne(() => BlockProgress, { onDelete: 'CASCADE' }) - block!: BlockProgress; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - cid!: string; - - @Column({ - type: 'enum', - enum: StateKind - }) - kind!: StateKind; - - @Column('bytea') - data!: Buffer; -} diff --git a/packages/mobymask-watcher/src/entity/StateSyncStatus.ts b/packages/mobymask-watcher/src/entity/StateSyncStatus.ts deleted file mode 100644 index c795212f..00000000 --- a/packages/mobymask-watcher/src/entity/StateSyncStatus.ts +++ /dev/null @@ -1,17 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; - -@Entity() -export class StateSyncStatus { - @PrimaryGeneratedColumn() - id!: number; - - @Column('integer') - latestIndexedBlockNumber!: number; - - @Column('integer', { nullable: true }) - latestCheckpointBlockNumber!: number; -} diff --git a/packages/mobymask-watcher/src/entity/SyncStatus.ts b/packages/mobymask-watcher/src/entity/SyncStatus.ts deleted file mode 100644 index 19d0dfa7..00000000 --- a/packages/mobymask-watcher/src/entity/SyncStatus.ts +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; -import { SyncStatusInterface } from '@cerc-io/util'; - -@Entity() -export class SyncStatus implements SyncStatusInterface { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - chainHeadBlockHash!: string; - - @Column('integer') - chainHeadBlockNumber!: number; - - @Column('varchar', { length: 66 }) - latestIndexedBlockHash!: string; - - @Column('integer') - latestIndexedBlockNumber!: number; - - @Column('varchar', { length: 66 }) - latestCanonicalBlockHash!: string; - - @Column('integer') - latestCanonicalBlockNumber!: number; - - @Column('varchar', { length: 66 }) - initialIndexedBlockHash!: string; - - @Column('integer') - initialIndexedBlockNumber!: number; -} diff --git a/packages/mobymask-watcher/src/entity/_Owner.ts b/packages/mobymask-watcher/src/entity/_Owner.ts deleted file mode 100644 index cef39007..00000000 --- a/packages/mobymask-watcher/src/entity/_Owner.ts +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import { Entity, PrimaryGeneratedColumn, Column, Index } from 'typeorm'; - -@Entity() -@Index(['blockHash', 'contractAddress'], { unique: true }) -export class _Owner { - @PrimaryGeneratedColumn() - id!: number; - - @Column('varchar', { length: 66 }) - blockHash!: string; - - @Column('integer') - blockNumber!: number; - - @Column('varchar', { length: 42 }) - contractAddress!: string; - - @Column('varchar') - value!: string; - - @Column('text', { nullable: true }) - proof!: string; -} diff --git a/packages/mobymask-watcher/src/fill.ts b/packages/mobymask-watcher/src/fill.ts deleted file mode 100644 index 0cfffd06..00000000 --- a/packages/mobymask-watcher/src/fill.ts +++ /dev/null @@ -1,32 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import 'reflect-metadata'; -import debug from 'debug'; - -import { FillCmd } from '@cerc-io/cli'; - -import { Database } from './database'; -import { Indexer } from './indexer'; - -const log = debug('vulcanize:fill'); - -export const main = async (): Promise => { - const fillCmd = new FillCmd(); - await fillCmd.init(Database); - await fillCmd.initIndexer(Indexer); - - await fillCmd.exec(); -}; - -main().catch(err => { - log(err); -}).finally(() => { - process.exit(); -}); - -process.on('SIGINT', () => { - log(`Exiting process ${process.pid} with code 0`); - process.exit(0); -}); diff --git a/packages/mobymask-watcher/src/gql/index.ts b/packages/mobymask-watcher/src/gql/index.ts deleted file mode 100644 index 4732f682..00000000 --- a/packages/mobymask-watcher/src/gql/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * as mutations from './mutations'; -export * as queries from './queries'; -export * as subscriptions from './subscriptions'; diff --git a/packages/mobymask-watcher/src/gql/mutations/index.ts b/packages/mobymask-watcher/src/gql/mutations/index.ts deleted file mode 100644 index 0c3bd853..00000000 --- a/packages/mobymask-watcher/src/gql/mutations/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -import fs from 'fs'; -import path from 'path'; - -export const watchContract = fs.readFileSync(path.join(__dirname, 'watchContract.gql'), 'utf8'); diff --git a/packages/mobymask-watcher/src/gql/mutations/watchContract.gql b/packages/mobymask-watcher/src/gql/mutations/watchContract.gql deleted file mode 100644 index 2ecc74f7..00000000 --- a/packages/mobymask-watcher/src/gql/mutations/watchContract.gql +++ /dev/null @@ -1,3 +0,0 @@ -mutation watchContract($address: String!, $kind: String!, $checkpoint: Boolean!, $startingBlock: Int){ - watchContract(address: $address, kind: $kind, checkpoint: $checkpoint, startingBlock: $startingBlock) -} \ No newline at end of file diff --git a/packages/mobymask-watcher/src/gql/queries/_owner.gql b/packages/mobymask-watcher/src/gql/queries/_owner.gql deleted file mode 100644 index 90154467..00000000 --- a/packages/mobymask-watcher/src/gql/queries/_owner.gql +++ /dev/null @@ -1,8 +0,0 @@ -query _owner($blockHash: String!, $contractAddress: String!){ - _owner(blockHash: $blockHash, contractAddress: $contractAddress){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/mobymask-watcher/src/gql/queries/events.gql b/packages/mobymask-watcher/src/gql/queries/events.gql deleted file mode 100644 index eb41f427..00000000 --- a/packages/mobymask-watcher/src/gql/queries/events.gql +++ /dev/null @@ -1,40 +0,0 @@ -query events($blockHash: String!, $contractAddress: String!, $name: String){ - events(blockHash: $blockHash, contractAddress: $contractAddress, name: $name){ - block{ - cid - hash - number - timestamp - parentHash - } - tx{ - hash - index - from - to - } - contract - eventIndex - event{ - ... on DelegationTriggeredEvent { - principal - agent - } - ... on MemberStatusUpdatedEvent { - entity - isMember - } - ... on OwnershipTransferredEvent { - previousOwner - newOwner - } - ... on PhisherStatusUpdatedEvent { - entity - isPhisher - } - } - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/mobymask-watcher/src/gql/queries/eventsInRange.gql b/packages/mobymask-watcher/src/gql/queries/eventsInRange.gql deleted file mode 100644 index 42e16f6a..00000000 --- a/packages/mobymask-watcher/src/gql/queries/eventsInRange.gql +++ /dev/null @@ -1,40 +0,0 @@ -query eventsInRange($fromBlockNumber: Int!, $toBlockNumber: Int!){ - eventsInRange(fromBlockNumber: $fromBlockNumber, toBlockNumber: $toBlockNumber){ - block{ - cid - hash - number - timestamp - parentHash - } - tx{ - hash - index - from - to - } - contract - eventIndex - event{ - ... on DelegationTriggeredEvent { - principal - agent - } - ... on MemberStatusUpdatedEvent { - entity - isMember - } - ... on OwnershipTransferredEvent { - previousOwner - newOwner - } - ... on PhisherStatusUpdatedEvent { - entity - isPhisher - } - } - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/mobymask-watcher/src/gql/queries/getState.gql b/packages/mobymask-watcher/src/gql/queries/getState.gql deleted file mode 100644 index 3b8f6050..00000000 --- a/packages/mobymask-watcher/src/gql/queries/getState.gql +++ /dev/null @@ -1,15 +0,0 @@ -query getState($blockHash: String!, $contractAddress: String!, $kind: String){ - getState(blockHash: $blockHash, contractAddress: $contractAddress, kind: $kind){ - block{ - cid - hash - number - timestamp - parentHash - } - contractAddress - cid - kind - data - } -} \ No newline at end of file diff --git a/packages/mobymask-watcher/src/gql/queries/getStateByCID.gql b/packages/mobymask-watcher/src/gql/queries/getStateByCID.gql deleted file mode 100644 index 6c3c4fd8..00000000 --- a/packages/mobymask-watcher/src/gql/queries/getStateByCID.gql +++ /dev/null @@ -1,15 +0,0 @@ -query getStateByCID($cid: String!){ - getStateByCID(cid: $cid){ - block{ - cid - hash - number - timestamp - parentHash - } - contractAddress - cid - kind - data - } -} \ No newline at end of file diff --git a/packages/mobymask-watcher/src/gql/queries/index.ts b/packages/mobymask-watcher/src/gql/queries/index.ts deleted file mode 100644 index bdcdde02..00000000 --- a/packages/mobymask-watcher/src/gql/queries/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -import fs from 'fs'; -import path from 'path'; - -export const events = fs.readFileSync(path.join(__dirname, 'events.gql'), 'utf8'); -export const eventsInRange = fs.readFileSync(path.join(__dirname, 'eventsInRange.gql'), 'utf8'); -export const multiNonce = fs.readFileSync(path.join(__dirname, 'multiNonce.gql'), 'utf8'); -export const _owner = fs.readFileSync(path.join(__dirname, '_owner.gql'), 'utf8'); -export const isRevoked = fs.readFileSync(path.join(__dirname, 'isRevoked.gql'), 'utf8'); -export const isPhisher = fs.readFileSync(path.join(__dirname, 'isPhisher.gql'), 'utf8'); -export const isMember = fs.readFileSync(path.join(__dirname, 'isMember.gql'), 'utf8'); -export const getStateByCID = fs.readFileSync(path.join(__dirname, 'getStateByCID.gql'), 'utf8'); -export const getState = fs.readFileSync(path.join(__dirname, 'getState.gql'), 'utf8'); diff --git a/packages/mobymask-watcher/src/gql/queries/isMember.gql b/packages/mobymask-watcher/src/gql/queries/isMember.gql deleted file mode 100644 index f783ec3a..00000000 --- a/packages/mobymask-watcher/src/gql/queries/isMember.gql +++ /dev/null @@ -1,8 +0,0 @@ -query isMember($blockHash: String!, $contractAddress: String!, $key0: String!){ - isMember(blockHash: $blockHash, contractAddress: $contractAddress, key0: $key0){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/mobymask-watcher/src/gql/queries/isPhisher.gql b/packages/mobymask-watcher/src/gql/queries/isPhisher.gql deleted file mode 100644 index 0f4ff6ee..00000000 --- a/packages/mobymask-watcher/src/gql/queries/isPhisher.gql +++ /dev/null @@ -1,8 +0,0 @@ -query isPhisher($blockHash: String!, $contractAddress: String!, $key0: String!){ - isPhisher(blockHash: $blockHash, contractAddress: $contractAddress, key0: $key0){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/mobymask-watcher/src/gql/queries/isRevoked.gql b/packages/mobymask-watcher/src/gql/queries/isRevoked.gql deleted file mode 100644 index 5e1ed69e..00000000 --- a/packages/mobymask-watcher/src/gql/queries/isRevoked.gql +++ /dev/null @@ -1,8 +0,0 @@ -query isRevoked($blockHash: String!, $contractAddress: String!, $key0: String!){ - isRevoked(blockHash: $blockHash, contractAddress: $contractAddress, key0: $key0){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/mobymask-watcher/src/gql/queries/multiNonce.gql b/packages/mobymask-watcher/src/gql/queries/multiNonce.gql deleted file mode 100644 index 9bc400b1..00000000 --- a/packages/mobymask-watcher/src/gql/queries/multiNonce.gql +++ /dev/null @@ -1,8 +0,0 @@ -query multiNonce($blockHash: String!, $contractAddress: String!, $key0: String!, $key1: BigInt!){ - multiNonce(blockHash: $blockHash, contractAddress: $contractAddress, key0: $key0, key1: $key1){ - value - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/mobymask-watcher/src/gql/subscriptions/index.ts b/packages/mobymask-watcher/src/gql/subscriptions/index.ts deleted file mode 100644 index f12910c5..00000000 --- a/packages/mobymask-watcher/src/gql/subscriptions/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -import fs from 'fs'; -import path from 'path'; - -export const onEvent = fs.readFileSync(path.join(__dirname, 'onEvent.gql'), 'utf8'); diff --git a/packages/mobymask-watcher/src/gql/subscriptions/onEvent.gql b/packages/mobymask-watcher/src/gql/subscriptions/onEvent.gql deleted file mode 100644 index cff8741a..00000000 --- a/packages/mobymask-watcher/src/gql/subscriptions/onEvent.gql +++ /dev/null @@ -1,40 +0,0 @@ -subscription onEvent{ - onEvent{ - block{ - cid - hash - number - timestamp - parentHash - } - tx{ - hash - index - from - to - } - contract - eventIndex - event{ - ... on DelegationTriggeredEvent { - principal - agent - } - ... on MemberStatusUpdatedEvent { - entity - isMember - } - ... on OwnershipTransferredEvent { - previousOwner - newOwner - } - ... on PhisherStatusUpdatedEvent { - entity - isPhisher - } - } - proof{ - data - } - } -} \ No newline at end of file diff --git a/packages/mobymask-watcher/src/hooks.ts b/packages/mobymask-watcher/src/hooks.ts deleted file mode 100644 index f2ce6c45..00000000 --- a/packages/mobymask-watcher/src/hooks.ts +++ /dev/null @@ -1,129 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import { utils } from 'ethers'; - -import { ResultEvent } from '@cerc-io/util'; - -import { Indexer, KIND_PHISHERREGISTRY } from './indexer'; - -const INVOKE_SIGNATURE = 'invoke(((((address,uint256,bytes),((address,bytes32,(address,bytes)[]),bytes)[])[],(uint256,uint256)),bytes)[])'; -const CLAIM_IF_MEMBER_SIGNATURE = 'claimIfMember(string,bool)'; -const CLAIM_IF_PHISHER_SIGNATURE = 'claimIfPhisher(string,bool)'; - -/** - * Hook function to store an initial state. - * @param indexer Indexer instance. - * @param blockHash Hash of the concerned block. - * @param contractAddress Address of the concerned contract. - * @returns Data block to be stored. - */ -export async function createInitialState (indexer: Indexer, contractAddress: string, blockHash: string): Promise { - assert(indexer); - assert(blockHash); - assert(contractAddress); - - // Store an empty State. - const stateData: any = { - state: {} - }; - - // Use updateStateForElementaryType to update initial state with an elementary property. - // Eg. const stateData = updateStateForElementaryType(stateData, '_totalBalance', result.value.toString()); - - // Use updateStateForMappingType to update initial state with a nested property. - // Eg. const stateData = updateStateForMappingType(stateData, '_allowances', [owner, spender], allowance.value.toString()); - - // Return initial state data to be saved. - return stateData; -} - -/** - * Hook function to create state diff. - * @param indexer Indexer instance that contains methods to fetch the contract varaiable values. - * @param blockHash Block hash of the concerned block. - */ -export async function createStateDiff (indexer: Indexer, blockHash: string): Promise { - assert(indexer); - assert(blockHash); - - // Use indexer.createDiff() method to save custom state diff(s). -} - -/** - * Hook function to create state checkpoint - * @param indexer Indexer instance. - * @param contractAddress Address of the concerned contract. - * @param blockHash Block hash of the concerned block. - * @returns Whether to disable default checkpoint. If false, the state from this hook is updated with that from default checkpoint. - */ -export async function createStateCheckpoint (indexer: Indexer, contractAddress: string, blockHash: string): Promise { - assert(indexer); - assert(blockHash); - assert(contractAddress); - - // Use indexer.createStateCheckpoint() method to create a custom checkpoint. - - // Return false to update the state created by this hook by auto-generated checkpoint state. - // Return true to disable update of the state created by this hook by auto-generated checkpoint state. - return false; -} - -/** - * Event hook function. - * @param indexer Indexer instance that contains methods to fetch and update the contract values in the database. - * @param eventData ResultEvent object containing event information. - */ -export async function handleEvent (indexer: Indexer, eventData: ResultEvent): Promise { - assert(indexer); - assert(eventData); - - // Perform indexing for PhisherStatusUpdated and MemberStatusUpdated. - if (['PhisherStatusUpdatedEvent', 'MemberStatusUpdatedEvent'].includes(eventData.event.__typename)) { - const txData = await indexer.getFullTransaction(eventData.tx.hash, eventData.block.number); - const txDescription = getTxDescription(indexer, KIND_PHISHERREGISTRY, txData.input); - let txDescriptions = [txDescription]; - - if (txDescription.signature === INVOKE_SIGNATURE) { - // Parse transactions from batches if it is an invoke method in Delegatable contract. - txDescriptions = txDescription.args.signedInvocations - .reduce((txs: utils.TransactionDescription[], signedInvocation: any) => { - // Get transactions from signed invocations batch. - const batchTxs = signedInvocation.invocations.batch.map((invocation: any) => { - return getTxDescription(indexer, KIND_PHISHERREGISTRY, invocation.transaction.data); - }); - - txs.push(...batchTxs); - - return txs; - }, []); - } - - // Filter transactions for claimIfMember and claimIsPhisher methods. - txDescriptions = txDescriptions.filter((tx: utils.TransactionDescription) => { - return [CLAIM_IF_MEMBER_SIGNATURE, CLAIM_IF_PHISHER_SIGNATURE].includes(tx.signature); - }); - - for (const txDescription of txDescriptions) { - switch (txDescription.signature) { - case CLAIM_IF_MEMBER_SIGNATURE: - // Update isMember entry for the identifier in database. - await indexer.isMember(eventData.block.hash, eventData.contract, txDescription.args.identifier, true); - break; - case CLAIM_IF_PHISHER_SIGNATURE: - // Update isPhisher entry for the identifier in database. - await indexer.isPhisher(eventData.block.hash, eventData.contract, txDescription.args.identifier, true); - break; - } - } - } -} - -// Get transaction details from input data. -const getTxDescription = (indexer: Indexer, contractKind: string, data: string): utils.TransactionDescription => { - const contractInterface = indexer.getContractInterface(contractKind); - assert(contractInterface); - return contractInterface.parseTransaction({ data }); -}; diff --git a/packages/mobymask-watcher/src/indexer.ts b/packages/mobymask-watcher/src/indexer.ts deleted file mode 100644 index f83c1bc1..00000000 --- a/packages/mobymask-watcher/src/indexer.ts +++ /dev/null @@ -1,668 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import debug from 'debug'; -import { DeepPartial, FindConditions, FindManyOptions } from 'typeorm'; -import JSONbig from 'json-bigint'; -import { ethers } from 'ethers'; - -import { JsonFragment } from '@ethersproject/abi'; -import { JsonRpcProvider } from '@ethersproject/providers'; -import { EthClient } from '@cerc-io/ipld-eth-client'; -import { MappingKey, StorageLayout } from '@cerc-io/solidity-mapper'; -import { - Indexer as BaseIndexer, - IndexerInterface, - ValueResult, - ServerConfig, - JobQueue, - Where, - QueryOptions, - updateStateForElementaryType, - updateStateForMappingType, - BlockHeight, - StateKind, - StateStatus, - getFullTransaction, - ResultEvent, - getResultEvent, - DatabaseInterface, - Clients -} from '@cerc-io/util'; - -import PhisherRegistryArtifacts from './artifacts/PhisherRegistry.json'; -import { Database, ENTITIES } from './database'; -import { createInitialState, handleEvent, createStateDiff, createStateCheckpoint } from './hooks'; -import { Contract } from './entity/Contract'; -import { Event } from './entity/Event'; -import { SyncStatus } from './entity/SyncStatus'; -import { StateSyncStatus } from './entity/StateSyncStatus'; -import { BlockProgress } from './entity/BlockProgress'; -import { State } from './entity/State'; -import { IsMember } from './entity/IsMember'; -import { IsPhisher } from './entity/IsPhisher'; -import { IsRevoked } from './entity/IsRevoked'; -import { _Owner } from './entity/_Owner'; -import { MultiNonce } from './entity/MultiNonce'; - -const log = debug('vulcanize:indexer'); -const JSONbigNative = JSONbig({ useNativeBigInt: true }); - -export const KIND_PHISHERREGISTRY = 'PhisherRegistry'; - -export class Indexer implements IndexerInterface { - _db: Database; - _ethClient: EthClient; - _ethProvider: JsonRpcProvider; - _baseIndexer: BaseIndexer; - _serverConfig: ServerConfig; - - _abiMap: Map; - _storageLayoutMap: Map; - _contractMap: Map; - - constructor (serverConfig: ServerConfig, db: DatabaseInterface, clients: Clients, ethProvider: JsonRpcProvider, jobQueue: JobQueue) { - assert(db); - assert(clients.ethClient); - - this._db = db as Database; - this._ethClient = clients.ethClient; - this._ethProvider = ethProvider; - this._serverConfig = serverConfig; - this._baseIndexer = new BaseIndexer(this._serverConfig, this._db, this._ethClient, this._ethProvider, jobQueue); - - this._abiMap = new Map(); - this._storageLayoutMap = new Map(); - this._contractMap = new Map(); - - const { - abi: PhisherRegistryABI, - storageLayout: PhisherRegistryStorageLayout - } = PhisherRegistryArtifacts; - - assert(PhisherRegistryABI); - this._abiMap.set(KIND_PHISHERREGISTRY, PhisherRegistryABI); - assert(PhisherRegistryStorageLayout); - this._storageLayoutMap.set(KIND_PHISHERREGISTRY, PhisherRegistryStorageLayout); - this._contractMap.set(KIND_PHISHERREGISTRY, new ethers.utils.Interface(PhisherRegistryABI)); - } - - get serverConfig (): ServerConfig { - return this._serverConfig; - } - - get storageLayoutMap (): Map { - return this._storageLayoutMap; - } - - async init (): Promise { - await this._baseIndexer.fetchContracts(); - await this._baseIndexer.fetchStateStatus(); - } - - getResultEvent (event: Event): ResultEvent { - return getResultEvent(event); - } - - async multiNonce (blockHash: string, contractAddress: string, key0: string, key1: bigint, diff = false): Promise { - let entity = await this._db.getMultiNonce({ blockHash, contractAddress, key0, key1 }); - - if (entity) { - log('multiNonce: db hit.'); - } else { - log('multiNonce: db miss, fetching from upstream server'); - - entity = await this._getStorageEntity( - blockHash, - contractAddress, - MultiNonce, - 'multiNonce', - { key0, key1 }, - BigInt(0) - ); - - await this._db.saveMultiNonce(entity); - - if (diff) { - const stateUpdate = updateStateForMappingType({}, 'multiNonce', [key0.toString(), key1.toString()], entity.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - } - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - async _owner (blockHash: string, contractAddress: string, diff = false): Promise { - let entity = await this._db._getOwner({ blockHash, contractAddress }); - - if (entity) { - log('_owner: db hit.'); - } else { - log('_owner: db miss, fetching from upstream server'); - - entity = await this._getStorageEntity( - blockHash, - contractAddress, - _Owner, - '_owner', - {}, - '' - ); - - await this._db._saveOwner(entity); - - if (diff) { - const stateUpdate = updateStateForElementaryType({}, '_owner', entity.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - } - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - async isRevoked (blockHash: string, contractAddress: string, key0: string, diff = false): Promise { - let entity = await this._db.getIsRevoked({ blockHash, contractAddress, key0 }); - - if (entity) { - log('isRevoked: db hit.'); - } else { - log('isRevoked: db miss, fetching from upstream server'); - - entity = await this._getStorageEntity( - blockHash, - contractAddress, - IsRevoked, - 'isRevoked', - { key0 }, - false - ); - - await this._db.saveIsRevoked(entity); - - if (diff) { - const stateUpdate = updateStateForMappingType({}, 'isRevoked', [key0.toString()], entity.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - } - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - async isPhisher (blockHash: string, contractAddress: string, key0: string, diff = false): Promise { - let entity = await this._db.getIsPhisher({ blockHash, contractAddress, key0 }); - - if (entity) { - log('isPhisher: db hit.'); - } else { - log('isPhisher: db miss, fetching from upstream server'); - - entity = await this._getStorageEntity( - blockHash, - contractAddress, - IsPhisher, - 'isPhisher', - { key0 }, - false - ); - - await this._db.saveIsPhisher(entity); - - if (diff) { - const stateUpdate = updateStateForMappingType({}, 'isPhisher', [key0.toString()], entity.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - } - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - async isMember (blockHash: string, contractAddress: string, key0: string, diff = false): Promise { - let entity = await this._db.getIsMember({ blockHash, contractAddress, key0 }); - - if (entity) { - log('isMember: db hit.'); - } else { - log('isMember: db miss, fetching from upstream server'); - - entity = await this._getStorageEntity( - blockHash, - contractAddress, - IsMember, - 'isMember', - { key0 }, - false - ); - - await this._db.saveIsMember(entity); - - if (diff) { - const stateUpdate = updateStateForMappingType({}, 'isMember', [key0.toString()], entity.value.toString()); - await this.createDiffStaged(contractAddress, blockHash, stateUpdate); - } - } - - return { - value: entity.value, - proof: JSON.parse(entity.proof) - }; - } - - async _getStorageEntity ( - blockHash: string, - contractAddress: string, - entity: new () => Entity, - storageVariableName: string, - mappingKeys: {[key: string]: any}, - defaultValue: any - ): Promise { - const [{ number }, syncStatus] = await Promise.all([ - this._ethProvider.send('eth_getHeaderByHash', [blockHash]), - this.getSyncStatus() - ]); - - const blockNumber = ethers.BigNumber.from(number).toNumber(); - - let result: ValueResult = { - value: defaultValue - }; - - if (syncStatus && blockNumber < syncStatus.initialIndexedBlockNumber) { - const entityFields: any = { blockNumber, contractAddress, ...mappingKeys }; - const entityData: any = await this._db.getPrevEntity(entity, entityFields); - - if (entityData) { - result = { - value: entityData.value, - proof: JSON.parse(entityData.proof) - }; - } - } else { - const storageLayout = this._storageLayoutMap.get(KIND_PHISHERREGISTRY); - assert(storageLayout); - - result = await this._baseIndexer.getStorageValue( - storageLayout, - blockHash, - contractAddress, - storageVariableName, - ...Object.values(mappingKeys) - ); - } - - return { - blockHash, - blockNumber, - contractAddress, - ...mappingKeys, - value: result.value, - proof: result.proof ? JSONbigNative.stringify(result.proof) : null - } as any; - } - - async getStorageValue (storageLayout: StorageLayout, blockHash: string, contractAddress: string, variable: string, ...mappingKeys: MappingKey[]): Promise { - return this._baseIndexer.getStorageValue( - storageLayout, - blockHash, - contractAddress, - variable, - ...mappingKeys - ); - } - - async getEntitiesForBlock (blockHash: string, tableName: string): Promise { - return this._db.getEntitiesForBlock(blockHash, tableName); - } - - async processInitialState (contractAddress: string, blockHash: string): Promise { - // Call initial state hook. - return createInitialState(this, contractAddress, blockHash); - } - - async processStateCheckpoint (contractAddress: string, blockHash: string): Promise { - // Call checkpoint hook. - return createStateCheckpoint(this, contractAddress, blockHash); - } - - async processCanonicalBlock (blockHash: string): Promise { - console.time('time:indexer#processCanonicalBlock-finalize_auto_diffs'); - // Finalize staged diff blocks if any. - await this._baseIndexer.finalizeDiffStaged(blockHash); - console.timeEnd('time:indexer#processCanonicalBlock-finalize_auto_diffs'); - - // Call custom stateDiff hook. - await createStateDiff(this, blockHash); - } - - async processCheckpoint (blockHash: string): Promise { - // Return if checkpointInterval is <= 0. - const checkpointInterval = this._serverConfig.checkpointInterval; - if (checkpointInterval <= 0) return; - - console.time('time:indexer#processCheckpoint-checkpoint'); - await this._baseIndexer.processCheckpoint(this, blockHash, checkpointInterval); - console.timeEnd('time:indexer#processCheckpoint-checkpoint'); - } - - async processCLICheckpoint (contractAddress: string, blockHash?: string): Promise { - return this._baseIndexer.processCLICheckpoint(this, contractAddress, blockHash); - } - - async getPrevState (blockHash: string, contractAddress: string, kind?: string): Promise { - return this._db.getPrevState(blockHash, contractAddress, kind); - } - - async getLatestState (contractAddress: string, kind: StateKind | null, blockNumber?: number): Promise { - return this._db.getLatestState(contractAddress, kind, blockNumber); - } - - async getStatesByHash (blockHash: string): Promise { - return this._baseIndexer.getStatesByHash(blockHash); - } - - async getStateByCID (cid: string): Promise { - return this._baseIndexer.getStateByCID(cid); - } - - async getStates (where: FindConditions): Promise { - return this._db.getStates(where); - } - - getStateData (state: State): any { - return this._baseIndexer.getStateData(state); - } - - // Method used to create auto diffs (diff_staged). - async createDiffStaged (contractAddress: string, blockHash: string, data: any): Promise { - console.time('time:indexer#createDiffStaged-auto_diff'); - await this._baseIndexer.createDiffStaged(contractAddress, blockHash, data); - console.timeEnd('time:indexer#createDiffStaged-auto_diff'); - } - - // Method to be used by createStateDiff hook. - async createDiff (contractAddress: string, blockHash: string, data: any): Promise { - const block = await this.getBlockProgress(blockHash); - assert(block); - - await this._baseIndexer.createDiff(contractAddress, block, data); - } - - // Method to be used by createStateCheckpoint hook. - async createStateCheckpoint (contractAddress: string, blockHash: string, data: any): Promise { - const block = await this.getBlockProgress(blockHash); - assert(block); - - return this._baseIndexer.createStateCheckpoint(contractAddress, block, data); - } - - // Method to be used by export-state CLI. - async createCheckpoint (contractAddress: string, blockHash: string): Promise { - const block = await this.getBlockProgress(blockHash); - assert(block); - - return this._baseIndexer.createCheckpoint(this, contractAddress, block); - } - - async saveOrUpdateState (state: State): Promise { - return this._baseIndexer.saveOrUpdateState(state); - } - - async removeStates (blockNumber: number, kind: StateKind): Promise { - await this._baseIndexer.removeStates(blockNumber, kind); - } - - async triggerIndexingOnEvent (event: Event): Promise { - const resultEvent = this.getResultEvent(event); - - // Call custom hook function for indexing on event. - await handleEvent(this, resultEvent); - } - - async processEvent (event: Event): Promise { - // Trigger indexing of data based on the event. - await this.triggerIndexingOnEvent(event); - } - - async processBlock (blockProgress: BlockProgress): Promise { - console.time('time:indexer#processBlock-init_state'); - // Call a function to create initial state for contracts. - await this._baseIndexer.createInit(this, blockProgress.blockHash, blockProgress.blockNumber); - console.timeEnd('time:indexer#processBlock-init_state'); - } - - parseEventNameAndArgs (kind: string, logObj: any): any { - const { topics, data } = logObj; - - const contract = this._contractMap.get(kind); - assert(contract); - - const logDescription = contract.parseLog({ data, topics }); - - const { eventName, eventInfo, eventSignature } = this._baseIndexer.parseEvent(logDescription); - - return { - eventName, - eventInfo, - eventSignature - }; - } - - async getStateSyncStatus (): Promise { - return this._db.getStateSyncStatus(); - } - - async updateStateSyncStatusIndexedBlock (blockNumber: number, force?: boolean): Promise { - const dbTx = await this._db.createTransactionRunner(); - let res; - - try { - res = await this._db.updateStateSyncStatusIndexedBlock(dbTx, blockNumber, force); - await dbTx.commitTransaction(); - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - - return res; - } - - async updateStateSyncStatusCheckpointBlock (blockNumber: number, force?: boolean): Promise { - const dbTx = await this._db.createTransactionRunner(); - let res; - - try { - res = await this._db.updateStateSyncStatusCheckpointBlock(dbTx, blockNumber, force); - await dbTx.commitTransaction(); - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - - return res; - } - - async getLatestCanonicalBlock (): Promise { - const syncStatus = await this.getSyncStatus(); - assert(syncStatus); - - const latestCanonicalBlock = await this.getBlockProgress(syncStatus.latestCanonicalBlockHash); - assert(latestCanonicalBlock); - - return latestCanonicalBlock; - } - - async getLatestStateIndexedBlock (): Promise { - return this._baseIndexer.getLatestStateIndexedBlock(); - } - - async watchContract (address: string, kind: string, checkpoint: boolean, startingBlock: number): Promise { - return this._baseIndexer.watchContract(address, kind, checkpoint, startingBlock); - } - - updateStateStatusMap (address: string, stateStatus: StateStatus): void { - this._baseIndexer.updateStateStatusMap(address, stateStatus); - } - - cacheContract (contract: Contract): void { - return this._baseIndexer.cacheContract(contract); - } - - async saveEventEntity (dbEvent: Event): Promise { - return this._baseIndexer.saveEventEntity(dbEvent); - } - - async getEventsByFilter (blockHash: string, contract?: string, name?: string): Promise> { - return this._baseIndexer.getEventsByFilter(blockHash, contract, name); - } - - isWatchedContract (address : string): Contract | undefined { - return this._baseIndexer.isWatchedContract(address); - } - - getContractsByKind (kind: string): Contract[] { - return this._baseIndexer.getContractsByKind(kind); - } - - async getProcessedBlockCountForRange (fromBlockNumber: number, toBlockNumber: number): Promise<{ expected: number, actual: number }> { - return this._baseIndexer.getProcessedBlockCountForRange(fromBlockNumber, toBlockNumber); - } - - async getEventsInRange (fromBlockNumber: number, toBlockNumber: number): Promise> { - return this._baseIndexer.getEventsInRange(fromBlockNumber, toBlockNumber, this._serverConfig.maxEventsBlockRange); - } - - async getSyncStatus (): Promise { - return this._baseIndexer.getSyncStatus(); - } - - async getBlocks (blockFilter: { blockHash?: string, blockNumber?: number }): Promise { - return this._baseIndexer.getBlocks(blockFilter); - } - - async updateSyncStatusIndexedBlock (blockHash: string, blockNumber: number, force = false): Promise { - return this._baseIndexer.updateSyncStatusIndexedBlock(blockHash, blockNumber, force); - } - - async updateSyncStatusChainHead (blockHash: string, blockNumber: number, force = false): Promise { - return this._baseIndexer.updateSyncStatusChainHead(blockHash, blockNumber, force); - } - - async updateSyncStatusCanonicalBlock (blockHash: string, blockNumber: number, force = false): Promise { - return this._baseIndexer.updateSyncStatusCanonicalBlock(blockHash, blockNumber, force); - } - - async getEvent (id: string): Promise { - return this._baseIndexer.getEvent(id); - } - - async getBlockProgress (blockHash: string): Promise { - return this._baseIndexer.getBlockProgress(blockHash); - } - - async getBlockProgressEntities (where: FindConditions, options: FindManyOptions): Promise { - return this._baseIndexer.getBlockProgressEntities(where, options); - } - - async getBlocksAtHeight (height: number, isPruned: boolean): Promise { - return this._baseIndexer.getBlocksAtHeight(height, isPruned); - } - - async saveBlockAndFetchEvents (block: DeepPartial): Promise<[BlockProgress, DeepPartial[]]> { - return this._saveBlockAndFetchEvents(block); - } - - async getBlockEvents (blockHash: string, where: Where, queryOptions: QueryOptions): Promise> { - return this._baseIndexer.getBlockEvents(blockHash, where, queryOptions); - } - - async removeUnknownEvents (block: BlockProgress): Promise { - return this._baseIndexer.removeUnknownEvents(Event, block); - } - - async markBlocksAsPruned (blocks: BlockProgress[]): Promise { - return this._baseIndexer.markBlocksAsPruned(blocks); - } - - async updateBlockProgress (block: BlockProgress, lastProcessedEventIndex: number): Promise { - return this._baseIndexer.updateBlockProgress(block, lastProcessedEventIndex); - } - - async getAncestorAtDepth (blockHash: string, depth: number): Promise { - return this._baseIndexer.getAncestorAtDepth(blockHash, depth); - } - - // Get latest block using eth client. - async getLatestBlock (): Promise { - const { block } = await this._ethClient.getBlockByHash(); - - return block; - } - - // Get full transaction data. - async getFullTransaction (txHash: string, blockNumber: number): Promise { - return getFullTransaction(this._ethClient, txHash, blockNumber); - } - - // Get contract interface for specified contract kind. - getContractInterface (kind: string): ethers.utils.Interface | undefined { - return this._contractMap.get(kind); - } - - async resetWatcherToBlock (blockNumber: number): Promise { - const entities = [...ENTITIES]; - await this._baseIndexer.resetWatcherToBlock(blockNumber, entities); - } - - async _saveBlockAndFetchEvents ({ - cid: blockCid, - blockHash, - blockNumber, - blockTimestamp, - parentHash - }: DeepPartial): Promise<[BlockProgress, DeepPartial[]]> { - assert(blockHash); - assert(blockNumber); - - const dbEvents = await this._baseIndexer.fetchEvents(blockHash, blockNumber, this.parseEventNameAndArgs.bind(this)); - - const dbTx = await this._db.createTransactionRunner(); - try { - const block = { - cid: blockCid, - blockHash, - blockNumber, - blockTimestamp, - parentHash - }; - - console.time(`time:indexer#_saveBlockAndFetchEvents-db-save-${blockNumber}`); - const blockProgress = await this._db.saveBlockWithEvents(dbTx, block, dbEvents); - await dbTx.commitTransaction(); - console.timeEnd(`time:indexer#_saveBlockAndFetchEvents-db-save-${blockNumber}`); - - return [blockProgress, []]; - } catch (error) { - await dbTx.rollbackTransaction(); - throw error; - } finally { - await dbTx.release(); - } - } -} diff --git a/packages/mobymask-watcher/src/job-runner.ts b/packages/mobymask-watcher/src/job-runner.ts deleted file mode 100644 index 92e57187..00000000 --- a/packages/mobymask-watcher/src/job-runner.ts +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import debug from 'debug'; - -import { JobRunnerCmd } from '@cerc-io/cli'; -import { JobRunner } from '@cerc-io/util'; - -import { Indexer } from './indexer'; -import { Database } from './database'; - -const log = debug('vulcanize:job-runner'); - -export const main = async (): Promise => { - const jobRunnerCmd = new JobRunnerCmd(); - await jobRunnerCmd.init(Database); - await jobRunnerCmd.initIndexer(Indexer); - - await jobRunnerCmd.exec(async (jobRunner: JobRunner): Promise => { - await jobRunner.subscribeBlockProcessingQueue(); - await jobRunner.subscribeEventProcessingQueue(); - await jobRunner.subscribeBlockCheckpointQueue(); - await jobRunner.subscribeHooksQueue(); - }); -}; - -main().then(() => { - log('Starting job runner...'); -}).catch(err => { - log(err); -}); - -process.on('uncaughtException', err => { - log('uncaughtException', err); -}); diff --git a/packages/mobymask-watcher/src/resolvers.ts b/packages/mobymask-watcher/src/resolvers.ts deleted file mode 100644 index 5a1fb6e1..00000000 --- a/packages/mobymask-watcher/src/resolvers.ts +++ /dev/null @@ -1,160 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import assert from 'assert'; -import BigInt from 'apollo-type-bigint'; -import debug from 'debug'; -import Decimal from 'decimal.js'; -import { GraphQLScalarType } from 'graphql'; - -import { ValueResult, gqlTotalQueryCount, gqlQueryCount, getResultState, IndexerInterface, EventWatcher } from '@cerc-io/util'; - -import { Indexer } from './indexer'; - -const log = debug('vulcanize:resolver'); - -export const createResolvers = async (indexerArg: IndexerInterface, eventWatcher: EventWatcher): Promise => { - const indexer = indexerArg as Indexer; - - return { - BigInt: new BigInt('bigInt'), - - BigDecimal: new GraphQLScalarType({ - name: 'BigDecimal', - description: 'BigDecimal custom scalar type', - parseValue (value) { - // value from the client - return new Decimal(value); - }, - serialize (value: Decimal) { - // value sent to the client - return value.toFixed(); - } - }), - - Event: { - __resolveType: (obj: any) => { - assert(obj.__typename); - - return obj.__typename; - } - }, - - Subscription: { - onEvent: { - subscribe: () => eventWatcher.getEventIterator() - } - }, - - Mutation: { - watchContract: async (_: any, { address, kind, checkpoint, startingBlock = 1 }: { address: string, kind: string, checkpoint: boolean, startingBlock: number }): Promise => { - log('watchContract', address, kind, checkpoint, startingBlock); - await indexer.watchContract(address, kind, checkpoint, startingBlock); - - return true; - } - }, - - Query: { - multiNonce: (_: any, { blockHash, contractAddress, key0, key1 }: { blockHash: string, contractAddress: string, key0: string, key1: bigint }): Promise => { - log('multiNonce', blockHash, contractAddress, key0, key1); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('multiNonce').inc(1); - - return indexer.multiNonce(blockHash, contractAddress, key0, key1); - }, - - _owner: (_: any, { blockHash, contractAddress }: { blockHash: string, contractAddress: string }): Promise => { - log('_owner', blockHash, contractAddress); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('_owner').inc(1); - - return indexer._owner(blockHash, contractAddress); - }, - - isRevoked: (_: any, { blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: string }): Promise => { - log('isRevoked', blockHash, contractAddress, key0); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('isRevoked').inc(1); - - return indexer.isRevoked(blockHash, contractAddress, key0); - }, - - isPhisher: (_: any, { blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: string }): Promise => { - log('isPhisher', blockHash, contractAddress, key0); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('isPhisher').inc(1); - - return indexer.isPhisher(blockHash, contractAddress, key0); - }, - - isMember: (_: any, { blockHash, contractAddress, key0 }: { blockHash: string, contractAddress: string, key0: string }): Promise => { - log('isMember', blockHash, contractAddress, key0); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('isMember').inc(1); - - return indexer.isMember(blockHash, contractAddress, key0); - }, - - events: async (_: any, { blockHash, contractAddress, name }: { blockHash: string, contractAddress: string, name?: string }) => { - log('events', blockHash, contractAddress, name); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('events').inc(1); - - const block = await indexer.getBlockProgress(blockHash); - if (!block || !block.isComplete) { - throw new Error(`Block hash ${blockHash} number ${block?.blockNumber} not processed yet`); - } - - const events = await indexer.getEventsByFilter(blockHash, contractAddress, name); - return events.map(event => indexer.getResultEvent(event)); - }, - - eventsInRange: async (_: any, { fromBlockNumber, toBlockNumber }: { fromBlockNumber: number, toBlockNumber: number }) => { - log('eventsInRange', fromBlockNumber, toBlockNumber); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('eventsInRange').inc(1); - - const events = await indexer.getEventsInRange(fromBlockNumber, toBlockNumber); - return events.map(event => indexer.getResultEvent(event)); - }, - - getStateByCID: async (_: any, { cid }: { cid: string }) => { - log('getStateByCID', cid); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('getStateByCID').inc(1); - - const state = await indexer.getStateByCID(cid); - - return state && state.block.isComplete ? getResultState(state) : undefined; - }, - - getState: async (_: any, { blockHash, contractAddress, kind }: { blockHash: string, contractAddress: string, kind: string }) => { - log('getState', blockHash, contractAddress, kind); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('getState').inc(1); - - const state = await indexer.getPrevState(blockHash, contractAddress, kind); - - return state && state.block.isComplete ? getResultState(state) : undefined; - }, - - getSyncStatus: async () => { - log('getSyncStatus'); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('getSyncStatus').inc(1); - - return indexer.getSyncStatus(); - }, - - latestBlock: async () => { - log('latestBlock'); - gqlTotalQueryCount.inc(1); - gqlQueryCount.labels('latestBlock').inc(1); - - return indexer.getLatestBlock(); - } - } - }; -}; diff --git a/packages/mobymask-watcher/src/schema.gql b/packages/mobymask-watcher/src/schema.gql deleted file mode 100644 index da107f9c..00000000 --- a/packages/mobymask-watcher/src/schema.gql +++ /dev/null @@ -1,117 +0,0 @@ -scalar BigInt - -scalar BigDecimal - -scalar Bytes - -type Block_height { - hash: Bytes - number: Int -} - -type Proof { - data: String! -} - -type ResultBoolean { - value: Boolean! - proof: Proof -} - -type ResultString { - value: String! - proof: Proof -} - -type ResultInt { - value: Int! - proof: Proof -} - -type ResultBigInt { - value: BigInt! - proof: Proof -} - -type _Block_ { - cid: String! - hash: String! - number: Int! - timestamp: Int! - parentHash: String! -} - -type _Transaction_ { - hash: String! - index: Int! - from: String! - to: String! -} - -type ResultEvent { - block: _Block_! - tx: _Transaction_! - contract: String! - eventIndex: Int! - event: Event! - proof: Proof -} - -union Event = DelegationTriggeredEvent | MemberStatusUpdatedEvent | OwnershipTransferredEvent | PhisherStatusUpdatedEvent - -type DelegationTriggeredEvent { - principal: String! - agent: String! -} - -type MemberStatusUpdatedEvent { - entity: String! - isMember: Boolean! -} - -type OwnershipTransferredEvent { - previousOwner: String! - newOwner: String! -} - -type PhisherStatusUpdatedEvent { - entity: String! - isPhisher: Boolean! -} - -type ResultState { - block: _Block_! - contractAddress: String! - cid: String! - kind: String! - data: String! -} - -type SyncStatus { - latestIndexedBlockHash: String! - latestIndexedBlockNumber: Int! - latestCanonicalBlockHash: String! - latestCanonicalBlockNumber: Int! -} - -type Query { - events(blockHash: String!, contractAddress: String!, name: String): [ResultEvent!] - eventsInRange(fromBlockNumber: Int!, toBlockNumber: Int!): [ResultEvent!] - multiNonce(blockHash: String!, contractAddress: String!, key0: String!, key1: BigInt!): ResultBigInt! - _owner(blockHash: String!, contractAddress: String!): ResultString! - isRevoked(blockHash: String!, contractAddress: String!, key0: String!): ResultBoolean! - isPhisher(blockHash: String!, contractAddress: String!, key0: String!): ResultBoolean! - isMember(blockHash: String!, contractAddress: String!, key0: String!): ResultBoolean! - getStateByCID(cid: String!): ResultState - getState(blockHash: String!, contractAddress: String!, kind: String): ResultState - getSyncStatus: SyncStatus - latestBlock: Block_height -} - -type Mutation { - watchContract(address: String!, kind: String!, checkpoint: Boolean!, startingBlock: Int): Boolean! -} - -type Subscription { - onEvent: ResultEvent! -} diff --git a/packages/mobymask-watcher/src/server.ts b/packages/mobymask-watcher/src/server.ts deleted file mode 100644 index a26bde87..00000000 --- a/packages/mobymask-watcher/src/server.ts +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// - -import fs from 'fs'; -import path from 'path'; -import 'reflect-metadata'; -import debug from 'debug'; - -import { ServerCmd } from '@cerc-io/cli'; - -import { createResolvers } from './resolvers'; -import { Indexer } from './indexer'; -import { Database } from './database'; - -const log = debug('vulcanize:server'); - -export const main = async (): Promise => { - const serverCmd = new ServerCmd(); - await serverCmd.init(Database); - await serverCmd.initIndexer(Indexer); - - const typeDefs = fs.readFileSync(path.join(__dirname, 'schema.gql')).toString(); - return serverCmd.exec(createResolvers, typeDefs); -}; - -main().then(() => { - log('Starting server...'); -}).catch(err => { - log(err); -}); diff --git a/packages/mobymask-watcher/src/types.ts b/packages/mobymask-watcher/src/types.ts deleted file mode 100644 index c4562172..00000000 --- a/packages/mobymask-watcher/src/types.ts +++ /dev/null @@ -1,3 +0,0 @@ -// -// Copyright 2021 Vulcanize, Inc. -// diff --git a/packages/mobymask-watcher/tsconfig.json b/packages/mobymask-watcher/tsconfig.json deleted file mode 100644 index 4e55bfd1..00000000 --- a/packages/mobymask-watcher/tsconfig.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "compilerOptions": { - /* Visit https://aka.ms/tsconfig.json to read more about this file */ - - /* Basic Options */ - // "incremental": true, /* Enable incremental compilation */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ - "lib": ["es2019"], /* Specify library files to be included in the compilation. */ - // "allowJs": true, /* Allow javascript files to be compiled. */ - // "checkJs": true, /* Report errors in .js files. */ - // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ - // "declaration": true, /* Generates corresponding '.d.ts' file. */ - // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - "sourceMap": true, /* Generates corresponding '.map' file. */ - // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "dist", /* Redirect output structure to the directory. */ - // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - // "composite": true, /* Enable project compilation */ - // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ - // "removeComments": true, /* Do not emit comments to output. */ - // "noEmit": true, /* Do not emit outputs. */ - // "importHelpers": true, /* Import emit helpers from 'tslib'. */ - "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ - // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* Enable strict null checks. */ - // "strictFunctionTypes": true, /* Enable strict checking of function types. */ - // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ - // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ - // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - - /* Additional Checks */ - // "noUnusedLocals": true, /* Report errors on unused locals. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ - - /* Module Resolution Options */ - // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ - // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ - // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ - // "typeRoots": [], /* List of folders to include type definitions from. */ - // "types": [], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ - // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - - /* Source Map Options */ - // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ - // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - - /* Experimental Options */ - "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ - // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - - /* Advanced Options */ - "skipLibCheck": true, /* Skip type checking of declaration files. */ - "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ - "resolveJsonModule": true /* Enabling the option allows importing JSON, and validating the types in that JSON file. */ - }, - "include": ["src/**/*"] -} diff --git a/packages/peer/package.json b/packages/peer/package.json index 3715569b..981156ef 100644 --- a/packages/peer/package.json +++ b/packages/peer/package.json @@ -56,6 +56,7 @@ "@types/chai": "^4.2.19", "@types/mocha": "^8.2.2", "@types/node": "16.11.7", + "@types/yargs": "^17.0.0", "@typescript-eslint/eslint-plugin": "^5.47.1", "@typescript-eslint/parser": "^5.47.1", "eslint": "^8.35.0", diff --git a/packages/solidity-mapper/package.json b/packages/solidity-mapper/package.json index eb8a053c..0750f75e 100644 --- a/packages/solidity-mapper/package.json +++ b/packages/solidity-mapper/package.json @@ -9,6 +9,7 @@ "@nomiclabs/hardhat-ethers": "^2.0.2", "@nomiclabs/hardhat-waffle": "^2.0.1", "@types/chai": "^4.2.18", + "@types/lodash": "^4.14.168", "@typescript-eslint/eslint-plugin": "^5.47.1", "@typescript-eslint/parser": "^5.47.1", "chai": "^4.3.4", diff --git a/packages/test/package.json b/packages/test/package.json index 002bc199..93827417 100644 --- a/packages/test/package.json +++ b/packages/test/package.json @@ -23,6 +23,7 @@ "devDependencies": { "@types/chai": "^4.2.19", "@types/mocha": "^8.2.2", + "@types/yargs": "^17.0.0", "@typescript-eslint/eslint-plugin": "^5.47.1", "@typescript-eslint/parser": "^5.47.1", "eslint": "^8.35.0", diff --git a/packages/tracing-client/package.json b/packages/tracing-client/package.json index c042d55c..813d3a03 100644 --- a/packages/tracing-client/package.json +++ b/packages/tracing-client/package.json @@ -25,6 +25,7 @@ "devDependencies": { "@typescript-eslint/eslint-plugin": "^5.47.1", "@typescript-eslint/parser": "^5.47.1", + "@types/yargs": "^17.0.0", "eslint": "^8.35.0", "eslint-config-semistandard": "^15.0.1", "eslint-config-standard": "^16.0.3", diff --git a/packages/util/package.json b/packages/util/package.json index b4e8ca12..5b614110 100644 --- a/packages/util/package.json +++ b/packages/util/package.json @@ -42,11 +42,14 @@ "@nomiclabs/hardhat-waffle": "^2.0.1", "@types/express": "^4.17.14", "@types/fs-extra": "^9.0.11", + "@types/json-bigint": "^1.0.0", "@types/js-yaml": "^4.0.4", + "@types/lodash": "^4.14.168", "@types/pg": "^8.6.5", "@types/ws": "^8.5.3", "@typescript-eslint/eslint-plugin": "^5.47.1", "@typescript-eslint/parser": "^5.47.1", + "copyfiles": "^2.4.1", "decimal.js": "^10.3.1", "eslint": "^8.35.0", "eslint-config-semistandard": "^15.0.1", diff --git a/yarn.lock b/yarn.lock index f42cdc13..f41393f0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3805,9 +3805,9 @@ "@types/node" "*" "@types/lodash@^4.14.168": - version "4.14.191" - resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.191.tgz#09511e7f7cba275acd8b419ddac8da9a6a79e2fa" - integrity sha512-BdZ5BCCvho3EIXw6wUCXHe7rS53AIDPLE+JzwgT+OsJk53oBfbSmZZ7CX4VaRoN78N+TJpFi9QPlfIVNmJYWxQ== + version "4.14.194" + resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.194.tgz#b71eb6f7a0ff11bff59fc987134a093029258a76" + integrity sha512-r22s9tAS7imvBt2lyHC9B8AGwWnXaYb1tY09oyLkXDs4vArpYJzw09nj8MLx5VfciBPGIb+ZwG0ssYnEPJxn/g== "@types/long@^4.0.0": version "4.0.2" @@ -3980,9 +3980,9 @@ integrity sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA== "@types/yargs@^17.0.0": - version "17.0.23" - resolved "https://registry.yarnpkg.com/@types/yargs/-/yargs-17.0.23.tgz#a7db3a2062c95ca1a5e0d5d5ddb6521cbc649e35" - integrity sha512-yuogunc04OnzGQCrfHx+Kk883Q4X0aSwmYZhKjI21m+SVYzjIbrWl8dOOwSv5hf2Um2pdCOXWo9isteZTNXUZQ== + version "17.0.24" + resolved "https://registry.yarnpkg.com/@types/yargs/-/yargs-17.0.24.tgz#b3ef8d50ad4aa6aecf6ddc97c580a00f5aa11902" + integrity sha512-6i0aC7jV6QzQB8ne1joVZ0eSFIstHsCrobmOtghM11yGlH0j43FKL2UhWdELkyps0zuf7qVTUVCCR+tgSlyLLw== dependencies: "@types/yargs-parser" "*" @@ -4508,11 +4508,6 @@ apollo-server-types@^3.8.0: apollo-reporting-protobuf "^3.4.0" apollo-server-env "^4.2.1" -apollo-type-bigint@^0.1.3: - version "0.1.3" - resolved "https://registry.npmjs.org/apollo-type-bigint/-/apollo-type-bigint-0.1.3.tgz" - integrity sha512-nyfwEWRZ+kon3Nnot20DufGm2EHZrkJoryYzw3soD+USdxhkcW434w1c/n+mjMLQDl86Z6EvlkvMX5Lordf2Wg== - app-root-path@^3.0.0: version "3.0.0" resolved "https://registry.npmjs.org/app-root-path/-/app-root-path-3.0.0.tgz" @@ -6444,7 +6439,7 @@ copy-descriptor@^0.1.0: copyfiles@^2.4.1: version "2.4.1" - resolved "https://registry.npmjs.org/copyfiles/-/copyfiles-2.4.1.tgz" + resolved "https://registry.yarnpkg.com/copyfiles/-/copyfiles-2.4.1.tgz#d2dcff60aaad1015f09d0b66e7f0f1c5cd3c5da5" integrity sha512-fereAvAvxDrQDOXybk3Qu3dPbOoKoysFMWtkY3mv5BsL8//OSZVL5DCLYqgRfY5cWirgRzlC+WSrxp6Bo3eNZg== dependencies: glob "^7.0.5" @@ -6545,7 +6540,7 @@ cross-fetch@^2.1.0, cross-fetch@^2.1.1: node-fetch "2.1.2" whatwg-fetch "2.0.4" -cross-fetch@^3.0.6, cross-fetch@^3.1.4: +cross-fetch@^3.1.4: version "3.1.5" resolved "https://registry.yarnpkg.com/cross-fetch/-/cross-fetch-3.1.5.tgz#e1389f44d9e7ba767907f7af8454787952ab534f" integrity sha512-lvb1SBsI0Z7GDwmuid+mU3kWVBwTVUbe7S0H52yaaAdQOXq2YktTCZdlAcNKFzE6QtRz0snpw9bNiPeOIkkQvw== @@ -8249,11 +8244,6 @@ extglob@^2.0.4: snapdragon "^0.8.1" to-regex "^3.0.1" -extract-files@^9.0.0: - version "9.0.0" - resolved "https://registry.yarnpkg.com/extract-files/-/extract-files-9.0.0.tgz#8a7744f2437f81f5ed3250ed9f1550de902fe54a" - integrity sha512-CvdFfHkC95B4bBBk36hcEmvdR2awOdhhVUYH6S/zrVj3477zven/fJMYg7121h4T1xHZC+tetUpubpAhxwI7hQ== - extsprintf@1.3.0: version "1.3.0" resolved "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz" @@ -9063,15 +9053,6 @@ graphql-compose@^9.0.3: dependencies: graphql-type-json "0.3.2" -graphql-request@^3.4.0: - version "3.7.0" - resolved "https://registry.yarnpkg.com/graphql-request/-/graphql-request-3.7.0.tgz#c7406e537084f8b9788541e3e6704340ca13055b" - integrity sha512-dw5PxHCgBneN2DDNqpWu8QkbbJ07oOziy8z+bK/TAXufsOLaETuVO4GkXrbs0WjhdKhBMN3BkpN/RIvUHkmNUQ== - dependencies: - cross-fetch "^3.0.6" - extract-files "^9.0.0" - form-data "^3.0.0" - graphql-subscriptions@^2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/graphql-subscriptions/-/graphql-subscriptions-2.0.0.tgz" @@ -12252,7 +12233,7 @@ nodemon@^2.0.7: noms@0.0.0: version "0.0.0" - resolved "https://registry.npmjs.org/noms/-/noms-0.0.0.tgz" + resolved "https://registry.yarnpkg.com/noms/-/noms-0.0.0.tgz#da8ebd9f3af9d6760919b27d9cdc8092a7332859" integrity sha512-lNDU9VJaOPxUmXcLb+HQFeUgQQPtMI24Gt6hgfuMHRJgMRHMF/qZ4HJD3GDru4sSw9IQl2jPjAYnQrdIeLbwow== dependencies: inherits "^2.0.1" @@ -15856,7 +15837,7 @@ unset-value@^1.0.0: untildify@^4.0.0: version "4.0.0" - resolved "https://registry.npmjs.org/untildify/-/untildify-4.0.0.tgz" + resolved "https://registry.yarnpkg.com/untildify/-/untildify-4.0.0.tgz#2bc947b953652487e4600949fb091e3ae8cd919b" integrity sha512-KK8xQ1mkzZeg9inewmFVDNkg3l5LUhoq9kN6iWYB/CC9YMG8HA+c1Q8HwDe6dEX7kErrEVNVBO3fWsVq5iDgtw== upath@^2.0.1: