-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathethereum.js
82 lines (67 loc) · 2.2 KB
/
ethereum.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const contract = require('truffle-contract');
const Web3 = require('web3');
const ipfs = require('./ipfs');
const db = require('./database');
const Web3Abi = require('web3-eth-abi');
const pinataBuild = require('./PinataHub.json');
const Pinata = contract(pinataBuild);
const provider = new Web3.providers.WebsocketProvider(process.env.WS_PROVIDER || 'ws://localhost:8546');
Pinata.setProvider(provider);
const web3 = new Web3(provider);
const all = Promise.all.bind(Promise);
const MY_ADDRESS = '0x0000000000000000000000000000000000001337';
function getSignature(event) {
return web3.utils.sha3(`${event.name}(${event.params.map(param => param.type).join(',')})`);
}
function getHashFromEvent(event, eventDef) {
const log = Web3Abi.decodeLog(eventDef.params, event.data.replace('0x', ''), event.topics);
for (var i = 0; i < eventDef.params.length; i++) {
const definition = eventDef.params[i];
if (definition.selected) {
return log[definition.name];
}
}
throw Error('Hash not found', log);
}
async function watchContract(address) {
console.log('Starting watcher for contract', address);
const contract = db.getContract(address);
const config = await ipfs.getConfig(contract.configHash);
console.log(config);
config.events.forEach(eventDef => {
const signature = getSignature(eventDef);
console.log(signature);
web3.eth.subscribe('logs', {
address: address,
topics: [signature],
})
.on('data', event => {
const hash = getHashFromEvent(event, eventDef);
console.log('adding hash', hash);
db.addHash(address, hash);
ipfs.pin.add(hash);
});
});
}
(async function() {
const pinata = await Pinata.deployed();
db.getContracts().forEach(({ address, configHash }) => {
if (configHash) {
watchContract(address);
}
});
pinata.ContractAddedClient({
filter: {
_client: MY_ADDRESS,
}
})
.on('data', async (data) => {
console.log('New Contract', data);
const { _contract, configHash } = data.returnValues;
if (!db.hasContract(_contract)) {
db.addContract(_contract);
}
db.setConfigHash(_contract, configHash);
watchContract(_contract);
});
})();