├── src ├── index.ts ├── types.ts ├── builtin.ts ├── abi.ts └── state.ts ├── .prettierignore ├── .gitignore ├── .vscode ├── extensions.json ├── settings.json └── launch.json ├── .editorconfig ├── tsconfig.json ├── .github └── workflows │ └── npm-publish.yml ├── package.json ├── .cspell.json ├── LICENSE ├── .eslintrc.json └── README.md /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './state' 2 | export * from './types' 3 | export * from './builtin' 4 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | # package.json is formatted by package managers, so we ignore it here 2 | package.json -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/* 2 | .nyc_output 3 | dist 4 | node_modules 5 | test 6 | src/**.js 7 | coverage 8 | *.log 9 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "dbaeumer.vscode-eslint", 4 | "esbenp.prettier-vscode", 5 | "eamodio.gitlens", 6 | "streetsidesoftware.code-spell-checker", 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.userWords": [], // only use words from .cspell.json 3 | "cSpell.enabled": true, 4 | "editor.formatOnSave": true, 5 | "typescript.tsdk": "node_modules/typescript/lib", 6 | "typescript.enablePromptUseWorkspaceTsdk": true 7 | } 8 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | end_of_line = lf 7 | indent_size = 4 8 | indent_style = tab 9 | insert_final_newline = true 10 | max_line_length = 80 11 | trim_trailing_whitespace = true 12 | 13 | [*.md] 14 | max_line_length = 0 15 | trim_trailing_whitespace = false 16 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ESNext", 4 | "module": "CommonJS", 5 | "lib": ["esnext"], 6 | "moduleResolution": "Node16", 7 | "esModuleInterop": true, 8 | "strict": true, 9 | "strictNullChecks": true, 10 | "resolveJsonModule": true, 11 | "skipLibCheck": true, 12 | "skipDefaultLibCheck": true, 13 | "outDir": "./dist", 14 | "sourceMap": true, 15 | "declaration": true 16 | }, 17 | "include": ["src/**/*"] 18 | } 19 | -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | on: 3 | push: 4 | branches: 5 | - "master" 6 | 7 | jobs: 8 | publish: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v3 12 | - uses: actions/setup-node@v3 13 | with: 14 | node-version: "18" 15 | - run: npm ci --ignore-scripts 16 | - run: npm run build 17 | - uses: JS-DevTools/npm-publish@v2 18 | with: 19 | token: ${{ secrets.NPM_TOKEN }} 20 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ether-state", 3 | "version": "0.2.1", 4 | "description": "Library for syncing state from contracts.", 5 | "repository": "git@github.com:0xjimmy/ether-state.git", 6 | "author": "James Galbraith ", 7 | "license": "MIT", 8 | "scripts": { 9 | "build": "tsc" 10 | }, 11 | "dependencies": { 12 | "ethers": "^6.7.1" 13 | }, 14 | "devDependencies": { 15 | "typescript": "4.9.4" 16 | }, 17 | "main": "dist/index.js", 18 | "types": "dist/index.d.ts", 19 | "files": [ 20 | "/dist" 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /.cspell.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.1", 3 | "$schema": "https://raw.githubusercontent.com/streetsidesoftware/cspell/master/cspell.schema.json", 4 | "language": "en", 5 | "words": [ 6 | "bitjson", 7 | "bitauth", 8 | "cimg", 9 | "circleci", 10 | "codecov", 11 | "commitlint", 12 | "dependabot", 13 | "editorconfig", 14 | "esnext", 15 | "execa", 16 | "exponentiate", 17 | "globby", 18 | "libauth", 19 | "mkdir", 20 | "prettierignore", 21 | "sandboxed", 22 | "transpiled", 23 | "typedoc", 24 | "untracked" 25 | ], 26 | "flagWords": [], 27 | "ignorePaths": [ 28 | "package.json", 29 | "package-lock.json", 30 | "yarn.lock", 31 | "tsconfig.json", 32 | "node_modules/**" 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | // To debug, make sure a *.spec.ts file is active in the editor, then run a configuration 5 | { 6 | "type": "node", 7 | "request": "launch", 8 | "name": "Debug Active Spec", 9 | "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/ava", 10 | "runtimeArgs": ["debug", "--break", "--serial", "${file}"], 11 | "port": 9229, 12 | "outputCapture": "std", 13 | "skipFiles": ["/**/*.js"], 14 | "preLaunchTask": "npm: build" 15 | // "smartStep": true 16 | }, 17 | { 18 | // Use this one if you're already running `yarn watch` 19 | "type": "node", 20 | "request": "launch", 21 | "name": "Debug Active Spec (no build)", 22 | "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/ava", 23 | "runtimeArgs": ["debug", "--break", "--serial", "${file}"], 24 | "port": 9229, 25 | "outputCapture": "std", 26 | "skipFiles": ["/**/*.js"] 27 | // "smartStep": true 28 | }] 29 | } 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 DecentralisedTech 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "parser": "@typescript-eslint/parser", 4 | "parserOptions": { "project": "./tsconfig.json" }, 5 | "env": { "es6": true }, 6 | "ignorePatterns": ["node_modules", "build", "coverage"], 7 | "plugins": ["import", "eslint-comments", "functional"], 8 | "extends": [ 9 | "eslint:recommended", 10 | "plugin:eslint-comments/recommended", 11 | "plugin:@typescript-eslint/recommended", 12 | "plugin:import/typescript", 13 | "plugin:functional/lite", 14 | "prettier", 15 | "prettier/@typescript-eslint" 16 | ], 17 | "globals": { "BigInt": true, "console": true, "WebAssembly": true }, 18 | "rules": { 19 | "@typescript-eslint/explicit-module-boundary-types": "off", 20 | "eslint-comments/disable-enable-pair": [ 21 | "error", 22 | { "allowWholeFile": true } 23 | ], 24 | "eslint-comments/no-unused-disable": "error", 25 | "import/order": [ 26 | "error", 27 | { "newlines-between": "always", "alphabetize": { "order": "asc" } } 28 | ], 29 | "sort-imports": [ 30 | "error", 31 | { "ignoreDeclarationSort": true, "ignoreCase": true } 32 | ] 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import { Result, Log, BytesLike, Interface, EventFilter } from 'ethers' 2 | 3 | export enum TriggerType { 4 | BLOCK, 5 | EVENT, 6 | TIME, 7 | } 8 | 9 | export type BlockTrigger = { type: TriggerType.BLOCK } 10 | export type TimeTrigger = { type: TriggerType.TIME, interval: number } 11 | export type EventTrigger = { type: TriggerType.EVENT, eventFilter: EventFilter } 12 | 13 | export type Trigger = BlockTrigger | EventTrigger | TimeTrigger 14 | 15 | export type ContractCall = { 16 | target: () => string 17 | interface: Interface 18 | selector: string 19 | } 20 | 21 | export type BlockAction = { 22 | trigger: BlockTrigger 23 | input: (blockNumber: bigint) => Array 24 | call: ContractCall 25 | output: (returnValues: Result, blockNumber: bigint) => unknown 26 | } 27 | 28 | export type TimeAction = { 29 | trigger: TimeTrigger 30 | input: (currentTime: number) => Array 31 | call: ContractCall 32 | output: (returnValues: Result, blockNumber: bigint) => unknown 33 | } 34 | 35 | export type EventAction = { 36 | trigger: EventTrigger 37 | input: (log: Log, blockNumber: bigint) => Array 38 | call: ContractCall 39 | output: (returnValues: Result, blockNumber: bigint, log: Log) => unknown 40 | } 41 | 42 | export type Action = BlockAction | TimeAction | EventAction 43 | -------------------------------------------------------------------------------- /src/builtin.ts: -------------------------------------------------------------------------------- 1 | import { Result } from "ethers"; 2 | import { Interface, getAddress } from "ethers"; 3 | import { ERC20ABI, MulticallABI } from "./abi"; 4 | import { Action, TriggerType, Trigger } from "./types"; 5 | 6 | export function createERC20BalanceAction(trigger: Trigger, tokenAddress: string, tokenOwner: string, setBalance: (balance: bigint) => unknown): Action { 7 | try { 8 | const token = getAddress(tokenAddress) 9 | const owner = getAddress(tokenOwner) 10 | return { 11 | trigger, 12 | call: { target: () => token, interface: new Interface(ERC20ABI), selector: 'balanceOf' }, 13 | input: () => [owner], 14 | output: (returnValues: Result) => setBalance(returnValues[0] as bigint) 15 | } as Action 16 | } catch { 17 | throw new Error("Invalid Address") 18 | } 19 | } 20 | 21 | export function createEtherBalanceAction(trigger: Trigger, userAddress: string, setBalance: (balance: bigint) => unknown, multicallAddress?: string): Action { 22 | try { 23 | const multicall2 = multicallAddress ? getAddress(multicallAddress) : "0x5ba1e12693dc8f9c48aad8770482f4739beed696" 24 | const owner = getAddress(userAddress) 25 | return { 26 | trigger: trigger, 27 | call: { target: () => multicall2, interface: new Interface(MulticallABI), selector: 'getEthBalance' }, 28 | input: () => [owner], 29 | output: (returnValues: Result) => setBalance(returnValues[0] as bigint) 30 | } as Action 31 | } catch { 32 | throw new Error("Invalid Address") 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/abi.ts: -------------------------------------------------------------------------------- 1 | import { InterfaceAbi } from 'ethers' 2 | 3 | export const MulticallABI: InterfaceAbi = [ 4 | 'function aggregate(tuple(address target, bytes callData)[] calls) returns (uint256 blockNumber, bytes[] returnData)', 5 | 'function blockAndAggregate(tuple(address target, bytes callData)[] calls) returns (uint256 blockNumber, bytes32 blockHash, tuple(bool success, bytes returnData)[] returnData)', 6 | 'function getBlockHash(uint256 blockNumber) view returns (bytes32 blockHash)', 7 | 'function getBlockNumber() view returns (uint256 blockNumber)', 8 | 'function getCurrentBlockCoinbase() view returns (address coinbase)', 9 | 'function getCurrentBlockDifficulty() view returns (uint256 difficulty)', 10 | 'function getCurrentBlockGasLimit() view returns (uint256 gaslimit)', 11 | 'function getCurrentBlockTimestamp() view returns (uint256 timestamp)', 12 | 'function getEthBalance(address addr) view returns (uint256 balance)', 13 | 'function getLastBlockHash() view returns (bytes32 blockHash)', 14 | 'function tryAggregate(bool requireSuccess, tuple(address target, bytes callData)[] calls) returns (tuple(bool success, bytes returnData)[] returnData)', 15 | 'function tryBlockAndAggregate(bool requireSuccess, tuple(address target, bytes callData)[] calls) returns (uint256 blockNumber, bytes32 blockHash, tuple(bool success, bytes returnData)[] returnData)' 16 | ] 17 | 18 | export const TokenMetadataABI: InterfaceAbi = [ 19 | 'function decimals() returns (string)', 20 | 'function symbol() returns (string)', 21 | 'function balanceOf(address addr) returns (uint)', 22 | ] 23 | 24 | export const ERC20ABI: InterfaceAbi = [ 25 | ...TokenMetadataABI, 26 | 'event Transfer(address indexed from, address indexed to, uint256 value)', 27 | 'event Approval(address indexed owner, address indexed spender, uint256 value)', 28 | 'function totalSupply() external view returns(uint256)', 29 | 'function balanceOf(address account) external view returns(uint256)', 30 | 'function transfer(address to, uint256 amount) external returns(bool)', 31 | 'function allowance(address owner, address spender) external view returns(uint256)', 32 | 'function approve(address spender, uint256 amount) external returns(bool)', 33 | 'function transferFrom(address from, address to, uint256 amount) external returns(bool)' 34 | ] 35 | 36 | export const ERC165ABI: InterfaceAbi = [ 37 | 'function supportsInterface(bytes4 interfaceId) external view returns (bool)' 38 | ] 39 | 40 | export const ERC721ABI: InterfaceAbi = [ 41 | ...TokenMetadataABI, 42 | ...ERC165ABI, 43 | 'function name() external view returns(string memory)', 44 | 'function symbol() external view returns(string memory)', 45 | 'function decimals() external view returns(uint8)', 46 | 'event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)', 47 | 'event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId)', 48 | 'event ApprovalForAll(address indexed owner, address indexed operator, bool approved)', 49 | 'function balanceOf(address owner) external view returns(uint256 balance)', 50 | 'function ownerOf(uint256 tokenId) external view returns(address owner)', 51 | 'function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external', 52 | 'function safeTransferFrom(address from, address to, uint256 tokenId) external', 53 | 'function transferFrom(address from, address to, uint256 tokenId) external', 54 | 'function approve(address to, uint256 tokenId) external', 55 | 'function setApprovalForAll(address operator, bool _approved) external', 56 | 'function getApproved(uint256 tokenId) external view returns(address operator)', 57 | 'function isApprovedForAll(address owner, address operator) external view returns(bool)' 58 | ] 59 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ether-state 2 | 3 | A Library for syncing state from contracts. 4 | Trigger Ethereum contract calls whenever there is a new block, matching event or by time interval. `ether-state` bundles calls with [Multicall2](https://github.com/mds1/multicall) to reduce the amount of RPC calls and tries to reduce the amount of event listeners needed for all actions. 5 | 6 | Originally designed for managing state in [Svelte Kit Ethers Template](https://github.com/0xjimmy/svelte-kit-ethers-template). 7 | 8 | ## TODO 9 | - [ ] Start using Multicall3 10 | - [ ] Add more default actions and action generators 11 | 12 | ## Basic Usage 13 | 14 | ```ts 15 | import { getDefaultProvider, formatEther, Interface, id, Log } from 'ethers'; 16 | import { EtherState, Actions, TriggerType } from 'ether-state'; 17 | 18 | const IERC20 = new Interface([ 19 | 'function totalSupply() external view returns (uint256)', 20 | 'function balanceOf(address) external view returns (uint256)', 21 | 'event Transfer(address indexed from, address indexed to, uint256 value)', 22 | ]); 23 | 24 | // Check totalSupply of DAI every block, check balance of every DAI recipient on Transfer event 25 | const actions: Actions[] = [ 26 | { 27 | trigger: { 28 | type: TriggerType.BLOCK 29 | }, 30 | input: () => [], 31 | call: { 32 | target: () => '0x6B175474E89094C44Da98b954EedeAC495271d0F', // DAI contract 33 | interface: IERC20, 34 | selector: 'totalSupply', 35 | }, 36 | output: (returnParams) => { 37 | console.log('DAI Total Supply:', formatEther(returnParams[0])); 38 | }, 39 | }, 40 | { 41 | trigger: { 42 | type: TriggerType.EVENT, 43 | eventFilter: { 44 | address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', 45 | topics: [id('Transfer(address,address,uint256)')] 46 | } 47 | }, 48 | // Use the transfer recipient as the input param for balanceOf call 49 | input: (log: Log) => { 50 | const event = IERC20.decodeEventLog( 51 | 'Transfer', 52 | log.data, 53 | log.topics 54 | ); 55 | console.log( 56 | `${event.from} sent ${formatEther(event.value)} DAI to ${ 57 | event.to 58 | }` 59 | ); 60 | return [event.to]; 61 | }, 62 | call: { 63 | target: () => '0x6B175474E89094C44Da98b954EedeAC495271d0F', // DAI contract 64 | interface: IERC20, 65 | selector: 'balanceOf', 66 | }, 67 | output: (returnParams) => { 68 | console.log('Recipents balance is now: ', formatEther(returnParams[0]), ' DAI'); 69 | }, 70 | }, 71 | ]; 72 | 73 | const provider = getDefaultProvider(); 74 | const etherState = new EtherState(actions, provider); 75 | ``` 76 | 77 | # API 78 | 79 | - [EtherState](#EtherState) 80 | - [Triggers](#Triggers) 81 | - [Actions](#Actions) 82 | - [BlockAction](#BlockAction) 83 | - [EventAction](#EventAction) 84 | - [TimeAction](#TimeAction) 85 | 86 | ## EtherState 87 | 88 | 89 | Takes an array of `Actions` and manages calling contracts based on their triggers. 90 | 91 | ```ts 92 | import { EtherState, Action, TriggerType } from 'ether-state'; 93 | import { getDefaultProvider } from 'ethers'; 94 | 95 | const provider = getDefaultProvider(); 96 | const actions: Action[] = []; 97 | 98 | // Create instance 99 | const etherState = new EtherState(actions, provider) 100 | 101 | // Manually trigger contract calls to all actions with BLOCK trigger 102 | etherState.update(TriggerType.BLOCK); 103 | 104 | // Destory instance, turn off all event listeners 105 | etherState.destroy(); 106 | ``` 107 | 108 | **Create new instance** -`new EtherState(actions: Action[], provider: Provider, options?: { customMulticallAddress?: string, populateTimeAndBlock?: boolean })` 109 | 110 | **Manually Trigger Updates** - `EtherState.update(type: TriggerType.TIME | TriggerType.BLOCK)` 111 | Triggers update calls to all Actions with trigger types of either TIME or BLOCK. 112 | 113 | **Stop Updates** = `EtherState.destroy()` 114 | Removes all event listeners and stops all updates 115 | 116 | ## Triggers 117 | 118 | There are 3 trigger types, `BLOCK`, `TIME` and `EVENT`. 119 | 120 | Time actions are triggered by setInterval, set the interval amount in ms. 121 | Event actions are triggered by a matching ethers' [EventFilter](https://docs.ethers.org/v6/api/providers/#EventFilter), the Log from the event filter and block is passed to the `inputs` method of the action. 122 | 123 | ```ts 124 | enum TriggerType { 125 | BLOCK, 126 | EVENT, 127 | TIME, 128 | } 129 | 130 | type BlockTrigger = { type: TriggerType.BLOCK } 131 | type TimeTrigger = { type: TriggerType.TIME, interval: number } 132 | type EventTrigger = { type: TriggerType.EVENT, eventFilter: EventFilter } 133 | ``` 134 | 135 | ## Actions 136 | 137 | There are 3 variation of `Action` for the 3 different trigger types. 138 | They all include trigger, input, call and output with type specific parameters for the input and output functions. 139 | 140 | The `input` function returns an array of input parameters for a contract function call. 141 | The `output` function gets passed the return value of the contract call as well as trigger specific data like the Log of an event triggered action. 142 | The `call` object defines the interface and function name to be called and a function that returns the contract address: 143 | ```ts 144 | type ContractCall = { 145 | target: () => string 146 | interface: Interface 147 | selector: string 148 | } 149 | 150 | ``` 151 | 152 | **Variations of Actions** 153 | 154 | ```ts 155 | type BlockAction = { 156 | trigger: BlockTrigger 157 | input: (blockNumber: bigint) => Array 158 | call: ContractCall 159 | output: (returnValues: Result, blockNumber: bigint) => unknown 160 | } 161 | 162 | type TimeAction = { 163 | trigger: TimeTrigger 164 | input: (currentTime: number) => Array 165 | call: ContractCall 166 | output: (returnValues: Result, blockNumber: bigint) => unknown 167 | } 168 | 169 | type EventAction = { 170 | trigger: EventTrigger 171 | input: (log: Log, blockNumber: bigint) => Array 172 | call: ContractCall 173 | output: (returnValues: Result, blockNumber: bigint, log: Log) => unknown 174 | } 175 | 176 | ``` 177 | -------------------------------------------------------------------------------- /src/state.ts: -------------------------------------------------------------------------------- 1 | import { Log } from 'ethers' 2 | import { Provider, Contract, BytesLike } from 'ethers' 3 | import { MulticallABI } from './abi' 4 | import { Action, BlockAction, EventAction, TimeAction, TriggerType } from './types' 5 | 6 | const MULTICALL2_ADDRESS = '0x5ba1e12693dc8f9c48aad8770482f4739beed696' 7 | 8 | export class EtherState { 9 | public blockNumber: bigint 10 | 11 | private provider: Provider 12 | private multicall: Contract 13 | 14 | private blockCallback: ((newBlock: number) => Promise) | undefined 15 | private timeActions: { intervalsIds: ReturnType[], callbacks: (() => Promise)[] } | undefined 16 | // private events: { intervalsIds: ReturnType[], callbacks: (() => Promise)[] } | undefined 17 | 18 | constructor( 19 | actions: Action[], 20 | provider: Provider, 21 | options?: { 22 | customMulticallAddress?: string, 23 | populateTimeAndBlock?: boolean 24 | } 25 | ) { 26 | this.provider = provider; 27 | this.multicall = new Contract( 28 | options && 'customMulticallAddress' in options && options.customMulticallAddress ? options.customMulticallAddress : MULTICALL2_ADDRESS, 29 | MulticallABI, 30 | this.provider 31 | ); 32 | this.blockNumber = 0n 33 | 34 | const blockActions = actions.filter(({ trigger }) => trigger.type === TriggerType.BLOCK) as BlockAction[] 35 | const timeActions = actions.filter(({ trigger }) => trigger.type === TriggerType.TIME) as TimeAction[] 36 | const eventActions = actions.filter(({ trigger }) => trigger.type === TriggerType.EVENT) as EventAction[] 37 | 38 | this.blockCallback = this.setupBlockActions(blockActions) 39 | this.timeActions = this.setupTimeActions(timeActions) 40 | this.setupEventActions(eventActions) 41 | 42 | // Populate if option selected 43 | if (options && 'populateTimeAndBlock' in options && options.populateTimeAndBlock) { 44 | this.update(TriggerType.BLOCK) 45 | this.update(TriggerType.TIME) 46 | } 47 | } 48 | 49 | private setupBlockActions(actions: BlockAction[]) { 50 | if (actions.length === 0) return undefined 51 | const callback = async (newBlock: number) => { 52 | const blockNumber = BigInt(newBlock) 53 | if (blockNumber > this.blockNumber) { 54 | this.blockNumber = blockNumber 55 | const contractCalls = actions.map((action) => ({ 56 | target: action.call.target(), 57 | callData: action.call.interface.encodeFunctionData( 58 | action.call.selector, 59 | action.input(blockNumber) 60 | ), 61 | })) 62 | const [multicallBlock, _, results]: [bigint, BytesLike, { success: boolean, returnData: BytesLike }[]] = await this.multicall.tryBlockAndAggregate.staticCall( 63 | false, 64 | contractCalls 65 | ) 66 | // Don't update with old data 67 | if (multicallBlock >= this.blockNumber) { 68 | results.forEach(({ success, returnData }, index) => { 69 | if (success) actions[index].output(actions[index].call.interface.decodeFunctionResult(actions[index].call.selector, returnData), multicallBlock) 70 | }) 71 | } 72 | } 73 | } 74 | this.provider.on('block', callback) 75 | return callback 76 | } 77 | 78 | private setupTimeActions(actions: TimeAction[]) { 79 | if (actions.length === 0) return undefined 80 | const uniqueIntervals = [...new Set(actions.map(({ trigger }) => trigger.interval))] 81 | const callbacks: (() => Promise)[] = [] 82 | const intervalsIds = uniqueIntervals.map((interval) => { 83 | const timeActions = actions.filter(({ trigger }) => trigger.interval === interval) 84 | const callback = async () => { 85 | const contractCalls = timeActions.map((action) => ({ 86 | target: action.call.target(), 87 | callData: action.call.interface.encodeFunctionData( 88 | action.call.selector, 89 | action.input(Date.now()) 90 | ), 91 | })) 92 | const [multicallBlock, _, results]: [bigint, BytesLike, { success: boolean, returnData: BytesLike }[]] = await this.multicall.tryBlockAndAggregate.staticCall( 93 | false, 94 | contractCalls 95 | ) 96 | results.forEach(({ success, returnData }, index) => { 97 | if (success) actions[index].output(actions[index].call.interface.decodeFunctionResult(actions[index].call.selector, returnData), multicallBlock) 98 | }) 99 | } 100 | callbacks.push(callback) 101 | return setInterval(callback, interval) 102 | }) 103 | return { intervalsIds, callbacks } 104 | } 105 | 106 | private setupEventActions(actions: EventAction[]) { 107 | if (actions.length === 0) return undefined 108 | const uniqueStringifiedEvents = [...new Set(actions.map(({ trigger }) => JSON.stringify(trigger.eventFilter)))] 109 | uniqueStringifiedEvents.forEach((stringifiedEvent) => { 110 | const matchingActions = actions.filter(({ trigger }) => JSON.stringify(trigger.eventFilter) === stringifiedEvent) 111 | const eventFilter = matchingActions[0].trigger.eventFilter 112 | this.provider.on(eventFilter, async (log: Log) => { 113 | const contractCalls = matchingActions.map((action) => ({ 114 | target: action.call.target(), 115 | callData: action.call.interface.encodeFunctionData( 116 | action.call.selector, 117 | action.input(log, BigInt(log.blockNumber)) 118 | ) 119 | })) 120 | const [multicallBlock, _, results]: [bigint, BytesLike, { success: boolean, returnData: BytesLike }[]] = await this.multicall.tryBlockAndAggregate.staticCall( 121 | false, 122 | contractCalls 123 | ) 124 | results.forEach(({ success, returnData }, index) => { 125 | if (success) matchingActions[index].output(matchingActions[index].call.interface.decodeFunctionResult(matchingActions[index].call.selector, returnData), multicallBlock, log) 126 | }) 127 | }) 128 | }) 129 | } 130 | 131 | // Manual update for any TIME or BLOCK actions states 132 | async update(type: TriggerType.TIME | TriggerType.BLOCK) { 133 | if (type === TriggerType.BLOCK && this.blockCallback) { 134 | const block = await this.provider.getBlockNumber() 135 | this.blockCallback(block) 136 | } 137 | if (type === TriggerType.TIME && this.timeActions) this.timeActions.callbacks.forEach(cb => cb()) 138 | } 139 | 140 | // Remove all event listners 141 | public destroy() { 142 | this.provider.removeAllListeners() 143 | if (this.timeActions) this.timeActions.intervalsIds.forEach((id) => clearInterval(id)) 144 | } 145 | } 146 | --------------------------------------------------------------------------------