|
| 1 | +import { Wallet, ethers } from 'ethers'; |
| 2 | +import { setTimeout } from 'timers/promises'; |
| 3 | + |
| 4 | +import { ChainId } from '../src/enums'; |
| 5 | +import { KVStoreClient, KVStoreUtils } from '../src/kvstore'; |
| 6 | + |
| 7 | +const LOCALHOST_RPC_URL = 'http://localhost:8545'; |
| 8 | + |
| 9 | +/** |
| 10 | + * Default is last signer account of local hardhat node. |
| 11 | + */ |
| 12 | +const PRIVATE_KEY = |
| 13 | + process.env.PRIVATE_KEY || |
| 14 | + '0xdf57089febbacf7ba0bc227dafbffa9fc08a93fdc68e1e42411a14efcf23656e'; |
| 15 | + |
| 16 | +const CREATED_AT_KV_KEY = 'created_at'; |
| 17 | +const UPDATED_AT_KV_KEY = 'last_touched_at'; |
| 18 | +const TOUCHED_TIMES_KV_KEY = 'touches_count'; |
| 19 | + |
| 20 | +const run = async () => { |
| 21 | + const provider = new ethers.JsonRpcProvider(LOCALHOST_RPC_URL); |
| 22 | + const wallet = new Wallet(PRIVATE_KEY, provider); |
| 23 | + |
| 24 | + const walletAddress = wallet.address; |
| 25 | + console.log(`Wallet address: ${walletAddress}`); |
| 26 | + |
| 27 | + const kvStoreClient = await KVStoreClient.build(wallet); |
| 28 | + const currentDate = new Date().toISOString(); |
| 29 | + |
| 30 | + const existingKeys = await KVStoreUtils.getKVStoreData( |
| 31 | + ChainId.LOCALHOST, |
| 32 | + walletAddress |
| 33 | + ); |
| 34 | + |
| 35 | + if (existingKeys.length === 0) { |
| 36 | + console.log('No KV data; initializing'); |
| 37 | + await kvStoreClient.setBulk( |
| 38 | + [CREATED_AT_KV_KEY, TOUCHED_TIMES_KV_KEY], |
| 39 | + [currentDate, '0'] |
| 40 | + ); |
| 41 | + } else { |
| 42 | + console.log('KV data found; updating'); |
| 43 | + const touchedTimesData = existingKeys.find( |
| 44 | + (d) => d.key === TOUCHED_TIMES_KV_KEY |
| 45 | + ) || { value: '0' }; |
| 46 | + |
| 47 | + let touchedTimes = Number(touchedTimesData.value); |
| 48 | + |
| 49 | + if (!Number.isSafeInteger(touchedTimes)) { |
| 50 | + touchedTimes = 0; |
| 51 | + } |
| 52 | + touchedTimes += 1; |
| 53 | + |
| 54 | + await kvStoreClient.setBulk( |
| 55 | + [UPDATED_AT_KV_KEY, TOUCHED_TIMES_KV_KEY], |
| 56 | + [currentDate, touchedTimes.toString()] |
| 57 | + ); |
| 58 | + } |
| 59 | + |
| 60 | + console.log('Finished setting values in KV store. Wait and read'); |
| 61 | + /** |
| 62 | + * Usually data is indexed almost immediately on local subgraph, |
| 63 | + * but there might be a delay if machine is slow or loaded, |
| 64 | + * so adding small delay here as well just in case. |
| 65 | + */ |
| 66 | + await setTimeout(1000 * 2); |
| 67 | + |
| 68 | + const kvData = await KVStoreUtils.getKVStoreData( |
| 69 | + ChainId.LOCALHOST, |
| 70 | + walletAddress |
| 71 | + ); |
| 72 | + console.log('Final KV store data:', kvData); |
| 73 | +}; |
| 74 | + |
| 75 | +(async () => { |
| 76 | + try { |
| 77 | + await run(); |
| 78 | + process.exit(0); |
| 79 | + } catch (error) { |
| 80 | + console.log('Failed', error); |
| 81 | + process.exit(1); |
| 82 | + } |
| 83 | +})(); |
0 commit comments