-
Notifications
You must be signed in to change notification settings - Fork 0
/
openai_oracle_service.js
225 lines (207 loc) · 5.34 KB
/
openai_oracle_service.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
require('dotenv').config();
const OpenAI = require('openai');
const Web3 = require('web3');
const fs = require('fs');
const LAST_BLOCK_FILE = 'lastBlock.txt';
const {
ETHEREUM_NODE_URL,
CONTRACT_ADDRESS,
ORACLE_ACCOUNT_ADDRESS,
PRIVATE_KEY
} = process.env;
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
// Connect to Ethereum node
const web3 = new Web3(ETHEREUM_NODE_URL);
// Contract ABI
const contractABI = [
{
"inputs": [
{
"internalType": "address",
"name": "_oracleAddress",
"type": "address"
}
],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "user",
"type": "address"
},
{
"indexed": false,
"internalType": "string",
"name": "question",
"type": "string"
}
],
"name": "NewQuestion",
"type": "event"
},
{
"inputs": [
{
"internalType": "string",
"name": "_question",
"type": "string"
}
],
"name": "askQuestion",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "getAnswer",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "oracleAddress",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "_user",
"type": "address"
},
{
"internalType": "string",
"name": "_answer",
"type": "string"
}
],
"name": "provideAnswer",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"name": "userQuestions",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"name": "userResponses",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
}
]
const contract = new web3.eth.Contract(contractABI, CONTRACT_ADDRESS);
// If lastBlock.txt doesn't exist, initialize with 0
if (!fs.existsSync(LAST_BLOCK_FILE)) {
fs.writeFileSync(LAST_BLOCK_FILE, '0');
}
// Read the last processed block from the file
let lastProcessedBlock = parseInt(fs.readFileSync(LAST_BLOCK_FILE, 'utf-8'));
// Make sure lastProcessedBlock is a valid number
if (isNaN(lastProcessedBlock)) {
console.warn("Invalid block number detected in lastBlock.txt. Resetting to 0.");
lastProcessedBlock = 0;
fs.writeFileSync(LAST_BLOCK_FILE, '0');
}
// Periodically check for events every 30 seconds
setInterval(async () => {
try {
const latestBlock = await web3.eth.getBlockNumber();
if (latestBlock <= lastProcessedBlock) {
console.log("No new blocks since last check. Waiting...");
return;
}
const events = await contract.getPastEvents('NewQuestion', {
fromBlock: lastProcessedBlock + 1,
toBlock: 'latest'
});
for (const event of events) {
const userAddress = event.returnValues.user;
const question = event.returnValues.question;
// Fetch answer from OPENAI service using the chat model
const completion = await openai.chat.completions.create({
messages: [{ role: 'user', content: question }],
model: 'gpt-3.5-turbo',
});
const answer = completion.choices[0].message.content.trim();
// Prepare the transaction
const tx = contract.methods.provideAnswer(userAddress, answer).encodeABI();
const nonce = await web3.eth.getTransactionCount(ORACLE_ACCOUNT_ADDRESS, 'pending');
const estimatedGas = await web3.eth.estimateGas({ to: CONTRACT_ADDRESS, data: tx });
console.log("Nonce",nonce);
const rawTransaction = {
from: ORACLE_ACCOUNT_ADDRESS,
to: CONTRACT_ADDRESS,
gas: estimatedGas,
nonce: nonce,
data: tx,
};
console.log(rawTransaction);
const accountFromPrivateKey = web3.eth.accounts.privateKeyToAccount(PRIVATE_KEY);
console.log('Account derived from PRIVATE_KEY:', accountFromPrivateKey.address);
// Sign & send the transaction
const signedTx = await web3.eth.accounts.signTransaction(rawTransaction, PRIVATE_KEY);
web3.eth.sendSignedTransaction(signedTx.rawTransaction)
.on('receipt', console.log)
.on('error', console.error);
// After successfully processing, update the last processed block
fs.writeFileSync(LAST_BLOCK_FILE, event.blockNumber.toString());
}
// Update the lastProcessedBlock for the next interval
lastProcessedBlock = latestBlock;
} catch (error) {
console.error("Error in periodic check:", error);
}
}, 30000); // 30000 milliseconds = 30 seconds