-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
228 lines (187 loc) · 7.04 KB
/
Copy pathindex.ts
File metadata and controls
228 lines (187 loc) · 7.04 KB
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
226
227
228
import {
Runner,
consensusMedianAggregation,
getNetwork,
handler,
cre,
type Runtime,
} from "@chainlink/cre-sdk";
import { hexToBase64, ConsensusAggregationByFields, median} from "@chainlink/cre-sdk";
import {
encodeAbiParameters,
type Address,
} from "viem";
import type { Config, EVMLog } from "./types";
import { HF_ONE, PCT_BASE } from "./types";
import { clampUint16 } from "./utils";
import { fetchFearGreed, fetchGeminiRiskScoreWithDebug } from "./http";
import { buildGeminiPrompt } from "./prompts";
import { decideBorrow } from "./decision";
import {
buildLogTrigger,
decodeBorrowRequested,
readBorrowGateRequest,
isDecided,
readPoolContext,
} from "./evm";
import { encodeDecisionPayload, writeDecisionReport } from "./report";
function initWorkflow(config: Config) {
const network = getNetwork({
chainFamily: "evm",
chainSelectorName: config.chainSelectorName,
isTestnet: true,
});
if (!network) throw new Error(`Network not found: ${config.chainSelectorName}`);
const evmClient = new cre.capabilities.EVMClient(network.chainSelector.selector);
const httpClient = new cre.capabilities.HTTPClient();
const trigger = buildLogTrigger(evmClient, config.borrowGateAddress);
const onLog = handler(trigger, (runtime: Runtime<Config>, log: EVMLog) => {
const cfg = runtime.config;
const { requestId, borrower, nullifier } = decodeBorrowRequested(log);
console.log("🧾 [RiskOrchestrator] BorrowRequested received");
console.log(` requestId=${requestId.toString()}`);
console.log(` borrower=${borrower}`);
console.log(` nullifier=${nullifier}`);
const req = readBorrowGateRequest(evmClient, runtime, cfg.borrowGateAddress, requestId);
console.log("🔎 [RiskOrchestrator] BorrowGate.requests()");
console.log(` executed=${req.executed}`);
console.log(` reqBorrower=${req.borrower}`);
console.log(` reqAmountWei=${req.amount.toString()}`);
console.log(` reqNullifier=${req.nullifier}`);
if (
req.executed ||
req.borrower.toLowerCase() !== borrower.toLowerCase() ||
req.nullifier.toLowerCase() !== nullifier.toLowerCase()
) {
console.log("⏭️ [RiskOrchestrator] Skipping: invalid/stale request");
return "Request invalid/stale; skipping";
}
const alreadyDecided = isDecided(evmClient, runtime, cfg.registryAddress, nullifier);
console.log(`🧷 [RiskOrchestrator] Registry.isDecided=${alreadyDecided}`);
if (alreadyDecided) {
console.log("⏭️ [RiskOrchestrator] Skipping: already decided");
return "Already decided; skipping";
}
let collValue: bigint, debt: bigint, liqThr: bigint, hfNow: bigint;
try {
({ collValue, debt, liqThr, hfNow } = readPoolContext(
evmClient,
runtime,
cfg.lendingPoolAddress,
borrower
));
console.log("🏦 [RiskOrchestrator] Pool context");
console.log(` collateralValue=${collValue.toString()}`);
console.log(` debt=${debt.toString()}`);
console.log(` liquidationThreshold=${liqThr.toString()}`);
console.log(` hfNowE18=${hfNow.toString()}`);
} catch (e: any) {
console.log("❌ [RiskOrchestrator] Pool/oracle read failed; writing reject reason=6");
console.log(` error=${String(e?.message ?? e)}`);
const payload = encodeAbiParameters(
[
{ type: "bytes32" },
{ type: "bool" },
{ type: "uint8" },
{ type: "uint16" },
{ type: "uint16" },
],
[nullifier, false, 6, 0, 65535]
);
const report = runtime
.report({
encodedPayload: hexToBase64(payload),
encoderName: "evm",
signingAlgo: "ecdsa",
hashingAlgo: "keccak256",
})
.result();
evmClient
.writeReport(runtime, {
receiver: cfg.receiverAddress,
report,
gasConfig: { gasLimit: cfg.gasLimit },
})
.result();
return `REJECT reason=6 (pool/oracle read failed: ${String(e?.message ?? e)})`;
}
const debtAfter = debt + req.amount;
const hfAfter =
debtAfter === 0n
? (2n ** 256n - 1n)
: (collValue * liqThr * HF_ONE) / (debtAfter * PCT_BASE);
const ltvBpsBig = collValue === 0n ? 65535n : (debtAfter * 10000n) / collValue;
const ltvBps = clampUint16(ltvBpsBig);
console.log("🧮 [RiskOrchestrator] Derived metrics");
console.log(` debtAfter=${debtAfter.toString()}`);
console.log(` hfAfterE18=${hfAfter.toString()}`);
console.log(` ltvBps=${ltvBps}`);
const fearGreed = httpClient
.sendRequest(runtime, fetchFearGreed, consensusMedianAggregation<number>())(cfg.riskApiUrl)
.result();
console.log(`📉 [RiskOrchestrator] fearGreed=${fearGreed} (min=${cfg.minFearGreed})`);
let riskScoreBp = 0;
let geminiStatus = -1;
let geminiSnippet = "";
console.log(`🧠 [RiskOrchestrator] Gemini enabled=${cfg.enableGemini}`);
if (cfg.enableGemini) {
const secret = runtime.getSecret({ id: "GEMINI_API_KEY" }).result();
const apiKey = secret?.value ?? "";
console.log(`🧠 [RiskOrchestrator] Gemini apiKeyPresent=${apiKey.length > 0}`);
console.log(`🧠 [RiskOrchestrator] Gemini model=${cfg.geminiModel}`);
const prompt = buildGeminiPrompt({
fearGreed,
hfNowE18: hfNow,
hfAfterE18: hfAfter,
ltvBpsAfter: ltvBps,
borrowAmountWei: req.amount,
});
console.log("🧠 [RiskOrchestrator] Gemini request -> sending");
const g = httpClient
.sendRequest(
runtime,
fetchGeminiRiskScoreWithDebug,
ConsensusAggregationByFields<{ score: number; status: number }>({
score: median,
status: median,
})
)(apiKey, cfg.geminiModel, prompt)
.result();
riskScoreBp = g.score;
geminiStatus = g.status;
console.log("🧠 [RiskOrchestrator] Gemini response <- aggregated");
console.log(` status=${geminiStatus}`);
console.log(` riskScoreBp=${riskScoreBp}`);
} else {
console.log("🧠 [RiskOrchestrator] Gemini skipped (enableGemini=false)");
}
const decision = decideBorrow({
fearGreed,
minFearGreed: cfg.minFearGreed,
hfAfter,
minHfAfter: BigInt(cfg.minHfAfterE18),
ltvBps,
riskScoreBp,
maxLtvBps: cfg.maxLtvBps,
reqAmount: req.amount,
maxBorrowAmount: BigInt(cfg.maxBorrowAmountWei),
});
console.log("✅ [RiskOrchestrator] Decision");
console.log(` approved=${decision.approved}`);
console.log(` reasonCode=${decision.reasonCode}`);
const payload = encodeDecisionPayload({
nullifier,
approved: decision.approved,
reasonCode: decision.reasonCode,
riskScoreBp,
ltvBps,
});
writeDecisionReport(evmClient, runtime, payload);
return `Decision=${decision.approved ? "APPROVE" : "REJECT"} reason=${decision.reasonCode} fearGreed=${fearGreed} ltvBps=${ltvBps} riskScoreBp=${riskScoreBp} geminiStatus=${geminiStatus} geminiRiskScoreBp="${geminiSnippet}"`;
});
return [onLog];
}
export async function main() {
const runner = await Runner.newRunner<Config>();
await runner.run(initWorkflow);
}