-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
81 lines (69 loc) · 2.42 KB
/
index.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
#!/usr/bin/env node
require('dotenv').config()
const {
TWITTER_API_KEY,
TWITTER_API_SECRET_KEY,
TWITTER_ACCESS_TOKEN,
TWITTER_ACCESS_TOKEN_SECRET,
TWITTER_MESSAGE_TEMPLATE,
WSURL,
ETHERSCAN_ABI_URL,
ETHERSCAN_API_KEY,
CONTRACT_ADDRESS,
CONTRACT_EVENTS } = process.env
const CONTRACT_EVENTS_ARRAY = CONTRACT_EVENTS.split(',')
const Web3 = require('web3')
const Twitter = require('twitter')
const restClient = require('node-rest-client-promise').Client()
const axios = require('axios')
const web3 = new Web3(new Web3.providers.WebsocketProvider(WSURL))
const twitterClient = new Twitter({
consumer_key: TWITTER_API_KEY,
consumer_secret: TWITTER_API_SECRET_KEY,
access_token_key: TWITTER_ACCESS_TOKEN,
access_token_secret: TWITTER_ACCESS_TOKEN_SECRET
})
async function postToTwitter(event) {
const msg = eval('`'+ TWITTER_MESSAGE_TEMPLATE + '`') // can replace this with message template
let opts = { status: msg }
// If you always use an image you can use `if (true)` here or remove conditional
if (TWITTER_MESSAGE_TEMPLATE.indexOf('metadata.data.image') >= 0) {
const img_url = event.metadata.data.image
// get png binary data
const result = await axios.request({
responseType: 'arraybuffer',
url: img_url,
method: 'get',
headers: {
'Content-Type': 'image/png', // if the image type changes this too
},
})
const data = result.data
const uploadResult = await twitterClient.post('media/upload', { media: data})
const media_id = uploadResult.media_id
opts = { status: msg, media_ids: media_id }
}
return twitterClient.post('statuses/update', opts, function(error, tweet, response) {
if (error) return console.log(JSON.stringify(error))
})
}
async function getContractAbi() {
const url = `${ETHERSCAN_ABI_URL}${CONTRACT_ADDRESS}&apiKey=${ETHERSCAN_API_KEY}`
const etherescan_response = await restClient.getPromise(url)
const contract_abi = JSON.parse(etherescan_response.data.result)
return contract_abi
}
async function eventQuery(){
const contract_abi = await getContractAbi()
const contract = new web3.eth.Contract(contract_abi, CONTRACT_ADDRESS)
let lastHash
contract.events.allEvents()
.on('data', (event) => {
if (CONTRACT_EVENTS_ARRAY.includes(event.event) && event.transactionHash !== lastHash) {
lastHash = event.transactionHash // dedupe
postToTwitter(event)
}
})
.on('error', console.error)
}
eventQuery()