-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
220 lines (194 loc) · 6.04 KB
/
Copy pathmain.ts
File metadata and controls
220 lines (194 loc) · 6.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
import {
CronCapability,
ConfidentialHTTPClient,
EVMClient,
getNetwork,
encodeCallMsg,
bytesToHex,
hexToBase64,
LATEST_BLOCK_NUMBER,
TxStatus,
handler,
consensusIdenticalAggregation,
ok,
json,
type ConfidentialHTTPSendRequester,
type Runtime,
Runner,
} from "@chainlink/cre-sdk"
import { encodeFunctionData, decodeFunctionResult, encodeAbiParameters, parseAbiParameters, type Address, type Abi, zeroAddress } from "viem"
import { z } from "zod"
import LienFiAuctionABI from "../abis/LienFiAuctionABI.json"
const ABI = LienFiAuctionABI as Abi
const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000"
const configSchema = z.object({
evms: z.array(
z.object({
chainSelectorName: z.string(),
contractAddress: z.string(),
gasLimit: z.string(),
})
),
schedule: z.string(),
url: z.string(),
owner: z.string(),
})
type Config = z.infer<typeof configSchema>
type SettlementResult = {
auctionId: string // bytes32 hex string
winner: string // address
price: string // uint256 decimal string
}
const submitSettlementToApi = (
sendRequester: ConfidentialHTTPSendRequester,
config: Config,
auctionId: string,
onChainHashes: string[]
): SettlementResult => {
const response = sendRequester
.sendRequest({
request: {
url: `${config.url}/settle`,
method: "POST",
bodyString: JSON.stringify({ auctionId, onChainHashes }),
multiHeaders: {
"X-Api-Key": { values: ["{{.apiKey}}"] },
"Content-Type": { values: ["application/json"] },
},
},
vaultDonSecrets: [
{ key: "apiKey", owner: config.owner },
{ key: "san_marino_aes_gcm_encryption_key", owner: config.owner },
],
})
.result()
if (!ok(response)) {
throw new Error(`Settlement API failed: ${response.statusCode}`)
}
return json(response) as SettlementResult
}
const readContract = (
evmClient: EVMClient,
runtime: Runtime<Config>,
to: Address,
functionName: string,
args?: readonly unknown[]
): `0x${string}` => {
const data = encodeFunctionData({ abi: ABI, functionName, args })
const result = evmClient
.callContract(runtime, {
call: encodeCallMsg({ from: zeroAddress, to, data }),
blockNumber: LATEST_BLOCK_NUMBER,
})
.result()
return bytesToHex(result.data)
}
const onCronTrigger = (runtime: Runtime<Config>): string => {
const { contractAddress, chainSelectorName } = runtime.config.evms[0]
const network = getNetwork({
chainFamily: "evm",
chainSelectorName,
isTestnet: true,
})
if (!network) {
throw new Error(`Network not found: ${chainSelectorName}`)
}
const evmClient = new EVMClient(network.chainSelector.selector)
// 1. Read activeAuctionId from the contract
const callData = encodeFunctionData({ abi: ABI, functionName: "activeAuctionId" })
const contractCall = evmClient
.callContract(runtime, {
call: encodeCallMsg({
from: zeroAddress,
to: contractAddress as Address,
data: callData,
}),
blockNumber: LATEST_BLOCK_NUMBER,
})
.result()
const activeAuctionId = decodeFunctionResult({
abi: ABI,
functionName: "activeAuctionId",
data: bytesToHex(contractCall.data),
}) as `0x${string}`
if (activeAuctionId === ZERO_BYTES32) {
runtime.log("No active auction, skipping settlement")
return "no-op"
}
runtime.log(`Active auction detected: ${activeAuctionId}`)
// 2. Read on-chain bid hashes for this auction
const bidCountRaw = readContract(
evmClient, runtime, contractAddress as Address,
"getBidCount", [activeAuctionId]
)
const bidCount = Number(
decodeFunctionResult({ abi: ABI, functionName: "getBidCount", data: bidCountRaw })
)
if (bidCount === 0) {
runtime.log("No bids registered on-chain, skipping settlement")
return "no-op"
}
const onChainHashes: string[] = []
for (let i = 0; i < bidCount; i++) {
const hashRaw = readContract(
evmClient, runtime, contractAddress as Address,
"bidHashes", [activeAuctionId, BigInt(i)]
)
const hash = decodeFunctionResult({
abi: ABI, functionName: "bidHashes", data: hashRaw,
}) as `0x${string}`
onChainHashes.push(hash)
}
runtime.log(`Found ${bidCount} on-chain bid hash(es)`)
// 3. Call private API with auctionId + on-chain hashes to determine winner
const confHTTPClient = new ConfidentialHTTPClient()
const result = confHTTPClient
.sendRequest(
runtime,
submitSettlementToApi,
consensusIdenticalAggregation<SettlementResult>()
)(runtime.config, activeAuctionId, onChainHashes)
.result()
runtime.log(`Settlement result: auctionId=${result.auctionId} winner=${result.winner} price=${result.price}`)
// 4. Encode settleAuction args and submit via DON-signed report
const { gasLimit } = runtime.config.evms[0]
const reportData = encodeAbiParameters(
parseAbiParameters("bytes32 auctionId, address winner, uint256 price"),
[result.auctionId as `0x${string}`, result.winner as Address, BigInt(result.price)]
)
const reportResponse = runtime
.report({
encodedPayload: hexToBase64(reportData),
encoderName: "evm",
signingAlgo: "ecdsa",
hashingAlgo: "keccak256",
})
.result()
const writeResult = evmClient
.writeReport(runtime, {
receiver: contractAddress,
report: reportResponse,
gasConfig: { gasLimit },
})
.result()
if (writeResult.txStatus !== TxStatus.SUCCESS) {
throw new Error(`settleAuction tx failed: ${writeResult.txStatus}`)
}
const txHash = bytesToHex(writeResult.txHash || new Uint8Array(32))
runtime.log(`settleAuction submitted: ${txHash}`)
runtime.log(`Explorer: https://sepolia.etherscan.io/tx/${txHash}`)
return txHash
}
const initWorkflow = (config: Config) => {
const cron = new CronCapability()
return [
handler(
cron.trigger({ schedule: config.schedule }),
onCronTrigger
),
]
}
export async function main() {
const runner = await Runner.newRunner<Config>({ configSchema })
await runner.run(initWorkflow)
}