forked from rareweave/glome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader-api.js
42 lines (40 loc) · 2.21 KB
/
reader-api.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
let { fetchTxContent } = require("./utils.js")
module.exports.readUpTo = async (contractId, timestamp) => {
console.log(global.servedContractsIds)
if (!global.servedContractsIds.has(contractId)) {
global.servedContractsIds.add(contractId)
throw new UncacheableError("Put dependency contract (" + contractId + ") to loadlist")
}
let isExecuted = await databases.isExecuted.get(contractId);
if (typeof isExecuted === "number") {
if (isExecuted === 0) {
let contractInstantiateTx = await databases.contracts.get(contractId)
if (!contractInstantiateTx || contractInstantiateTx.timestamp <= timestamp) {
throw new Error("No contract found")
} else {
return contractInstantiateTx.tags.find(tag => tag.name == "Init-State") ? JSON.parse(contractInstantiateTx.tags.find(tag => tag.name == "Init-State").value) : JSON.parse(await fetchTxContent(contractId))
}
} else {
let bestMatch = null
for await (let interaction of databases.interactions[contractId].getRange().map(({ value }) => (value)).filter(v => v.timestamp <= timestamp)) {
if (interaction.timestamp >= (bestMatch?.timestamp || 0)) {
bestMatch = interaction
}
}
if (!bestMatch) {
let contractInstantiateTx = await databases.contracts.get(contractId)
if (!contractInstantiateTx || contractInstantiateTx.timestamp <= timestamp) {
throw new Error("No contract found")
} else {
return contractInstantiateTx.tags.find(tag => tag.name == "Init-State") ? JSON.parse(contractInstantiateTx.tags.find(tag => tag.name == "Init-State").value) : JSON.parse(await fetchTxContent(contractId))
}
} else {
let bestMatchState = await databases.evaluationResults.get(contractId + bestMatch.id)
return bestMatchState?.state
}
}
} else {
throw new UncacheableError("Contract isn't executed yet")
}
}
class UncacheableError extends Error { constructor(message) { super(message); this.name = 'UncacheableError' } }