-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhspRelay.ts
More file actions
266 lines (243 loc) · 10.3 KB
/
Copy pathhspRelay.ts
File metadata and controls
266 lines (243 loc) · 10.3 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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/**
* hspRelay.ts
* HSP settlement relay (Pattern B — off-chain, zero-custody USDC settlement).
*
* When PayoutTrigger runs with settleOnchain=false, it emits PayoutExecuted as an
* *authorization* only (no native funds move on-chain). This relay listens for that
* event and performs the real HSP settlement to the beneficiary in USDC:
*
* 1. Build + EIP-712-sign a Mandate (payer intent) [hspMandate.ts]
* 2. POST /payments — register the signed mandate
* 3. USDC.transfer(...) — the payer's OWN wallet moves the USDC (zero-custody)
* 4. POST /payments/:id/observe — report the tx hash; adapter signs a Receipt
* 5. GET /payments/:id — fetch the receipt/decision for audit
*
* Enable by setting HSP_SETTLEMENT_ENABLED=true (+ the HSP_* / USDC_* vars) in .env,
* then runner.ts calls startRelay(). If disabled or misconfigured, it is a no-op.
*/
import { ethers } from "ethers";
import {
buildSignedMandate,
hspDomain,
mandateStructHash,
type SignedMandate,
} from "./hspMandate.js";
const PAYOUT_TRIGGER_ABI = [
"event PayoutExecuted(uint256 indexed policyId, address indexed beneficiary, uint256 amount, uint64 timestamp)",
];
const ERC20_ABI = [
"function transfer(address to, uint256 amount) returns (bool)",
"function balanceOf(address owner) view returns (uint256)",
"function decimals() view returns (uint8)",
];
export interface RelayConfig {
rpcUrl: string;
payoutTriggerAddress: string;
coordinatorUrl: string;
apiKey: string;
/** Chain registry name, e.g. "hashkey-testnet" | "hashkey". */
chainName: string;
chainId: number;
/** EIP-712 verifyingContract from GET /chains (0x...0001). */
verifyingContract: string;
/** USDC token address for this chain. */
usdcAddress: string;
/** Wallet that holds USDC and settles — the "payer". */
payerPrivateKey: string;
/** Payout amount in USDC base units (6 decimals). */
payoutUsdcBaseUnits: bigint;
/** Confirmations to wait on the USDC transfer before observing (2 testnet, 5 mainnet). */
confirmations: number;
/** Mandate validity window in seconds. */
deadlineSecs: number;
}
export interface SettlementResult {
policyId: number;
paymentId: string;
recipient: string;
amount: string;
transferTxHash: string;
receipt: unknown;
settledAt: string;
}
/** Build a RelayConfig from process.env, or return null if HSP settlement is not enabled/configured. */
export function relayConfigFromEnv(env: NodeJS.ProcessEnv): RelayConfig | null {
if ((env.HSP_SETTLEMENT_ENABLED ?? "").toLowerCase() !== "true") return null;
const required = {
coordinatorUrl: env.HSP_COORDINATOR_URL,
apiKey: env.HSP_API_KEY,
usdcAddress: env.USDC_ADDRESS,
payerPrivateKey: env.HSP_PAYER_PRIVATE_KEY || env.AI_SIGNER_PRIVATE_KEY,
payoutUsdc: env.PAYOUT_USDC_BASE_UNITS,
payoutTriggerAddress: env.PAYOUT_TRIGGER_ADDRESS,
};
const missing = Object.entries(required)
.filter(([, v]) => !v)
.map(([k]) => k);
if (missing.length) {
console.error(`[hspRelay] HSP_SETTLEMENT_ENABLED=true but missing: ${missing.join(", ")} — relay disabled`);
return null;
}
const chainId = Number(env.VITE_CHAIN_ID ?? env.HSP_CHAIN_ID ?? 133);
return {
rpcUrl: env.RPC_URL ?? "https://hashkeychain-testnet.alt.technology",
payoutTriggerAddress: required.payoutTriggerAddress!,
coordinatorUrl: required.coordinatorUrl!.replace(/\/$/, ""),
apiKey: required.apiKey!,
chainName: env.HSP_CHAIN_NAME ?? (chainId === 177 ? "hashkey" : "hashkey-testnet"),
chainId,
verifyingContract: env.HSP_VERIFYING_CONTRACT ?? "0x0000000000000000000000000000000000000001",
usdcAddress: required.usdcAddress!,
payerPrivateKey: required.payerPrivateKey!,
payoutUsdcBaseUnits: BigInt(required.payoutUsdc!),
confirmations: Number(env.HSP_CONFIRMATIONS ?? (chainId === 177 ? 5 : 2)),
deadlineSecs: Number(env.HSP_DEADLINE_SECS ?? 3600),
};
}
/**
* Start the HSP relay listener. Returns a cleanup function.
* De-dupes on policyId so a re-emitted event never double-settles.
*/
export function startRelay(config: RelayConfig): () => void {
console.log("[hspRelay] Starting HSP settlement relay (off-chain USDC, zero-custody)");
console.log(`[hspRelay] Coordinator : ${config.coordinatorUrl}`);
console.log(`[hspRelay] Chain : ${config.chainName} (${config.chainId})`);
console.log(`[hspRelay] USDC : ${config.usdcAddress}`);
console.log(`[hspRelay] Watching : ${config.payoutTriggerAddress}`);
const provider = new ethers.JsonRpcProvider(config.rpcUrl);
const trigger = new ethers.Contract(config.payoutTriggerAddress, PAYOUT_TRIGGER_ABI, provider);
const settledPolicies = new Set<number>();
const inFlight = new Set<number>();
const handler = async (...args: unknown[]) => {
const event = args[args.length - 1] as ethers.EventLog;
const policyId = Number(event.args[0]);
const beneficiary = String(event.args[1]);
if (settledPolicies.has(policyId) || inFlight.has(policyId)) {
console.log(`[hspRelay] policy=${policyId} already settled/in-flight — skipping`);
return;
}
inFlight.add(policyId);
console.log(`[hspRelay] PayoutExecuted — policy=${policyId} beneficiary=${beneficiary}`);
try {
const result = await settleViaHsp(config, policyId, beneficiary);
settledPolicies.add(policyId);
console.log(`[hspRelay] ✓ HSP settled — policy=${policyId} payment=${result.paymentId} tx=${result.transferTxHash}`);
} catch (err) {
console.error(`[hspRelay] ✗ HSP settlement failed — policy=${policyId}:`, err);
} finally {
inFlight.delete(policyId);
}
};
trigger.on("PayoutExecuted", handler);
return () => {
trigger.off("PayoutExecuted", handler);
console.log("[hspRelay] Relay stopped.");
};
}
/**
* Execute the full HSP settlement for one payout. Exported so it can be invoked
* directly (e.g. from a manual settle script) as well as by the event listener.
*/
export async function settleViaHsp(
config: RelayConfig,
policyId: number,
beneficiary: string
): Promise<SettlementResult> {
const provider = new ethers.JsonRpcProvider(config.rpcUrl);
const payer = new ethers.Wallet(config.payerPrivateKey, provider);
const domain = hspDomain(config.chainId, config.verifyingContract);
const deadline = Math.floor(Date.now() / 1000) + config.deadlineSecs;
// 1. Build + sign the mandate wrapper { body, signerProof, requiredCapabilities: [] }
const signed = await buildSignedMandate(payer, domain, {
recipient: beneficiary,
token: config.usdcAddress,
amount: config.payoutUsdcBaseUnits,
chainId: config.chainId,
deadline,
});
const localPaymentId = mandateStructHash(domain, signed.body);
// 2. Register the payment with the Coordinator
const paymentId = await registerPayment(config, signed, localPaymentId);
// 3. Payer's own wallet moves the USDC (zero-custody settlement)
const usdc = new ethers.Contract(config.usdcAddress, ERC20_ABI, payer);
const bal: bigint = await usdc.balanceOf(payer.address);
if (bal < config.payoutUsdcBaseUnits) {
throw new Error(
`Payer ${payer.address} has ${bal} USDC base units, needs ${config.payoutUsdcBaseUnits}. ` +
`Fund it with USDC (testnet: ${config.coordinatorUrl}/faucet/).`
);
}
const tx = await usdc.transfer(beneficiary, config.payoutUsdcBaseUnits);
console.log(`[hspRelay] USDC.transfer submitted tx=${tx.hash} — waiting ${config.confirmations} conf...`);
await tx.wait(config.confirmations);
// 4. Report the tx so the adapter observes + signs a receipt (202 = still confirming, retry)
const receipt = await observePayment(config, paymentId, tx.hash);
return {
policyId,
paymentId,
recipient: beneficiary,
amount: config.payoutUsdcBaseUnits.toString(),
transferTxHash: tx.hash,
receipt,
settledAt: new Date().toISOString(),
};
}
// ──────────────────────────────────────────────────────────────
// Coordinator REST API
// ──────────────────────────────────────────────────────────────
async function registerPayment(
config: RelayConfig,
mandate: SignedMandate,
localPaymentId: string
): Promise<string> {
const res = await fetch(`${config.coordinatorUrl}/payments`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${config.apiKey}`,
},
body: JSON.stringify({
chain: config.chainName,
mandate, // { body, signerProof, requiredCapabilities: [] }
attestations: [],
}),
signal: AbortSignal.timeout(30_000),
});
if (res.status !== 200 && res.status !== 201) {
const text = await res.text().catch(() => "(no body)");
throw new Error(`POST /payments → HTTP ${res.status}: ${text}`);
}
const data = (await res.json().catch(() => ({}))) as { paymentId?: string; id?: string };
// Prefer the server paymentId; fall back to the locally-computed idempotency key.
return data.paymentId ?? data.id ?? localPaymentId;
}
async function observePayment(
config: RelayConfig,
paymentId: string,
txHash: string
): Promise<unknown> {
const url = `${config.coordinatorUrl}/payments/${paymentId}/observe`;
// 202 = still confirming; retry with backoff until the adapter signs (200).
const maxAttempts = 10;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${config.apiKey}`,
},
body: JSON.stringify({ txHash }),
signal: AbortSignal.timeout(30_000),
});
if (res.status === 200) return res.json().catch(() => ({}));
if (res.status === 202) {
const waitMs = Math.min(2000 * attempt, 10_000);
console.log(`[hspRelay] observe pending (202) — attempt ${attempt}/${maxAttempts}, retry in ${waitMs}ms`);
await new Promise((r) => setTimeout(r, waitMs));
continue;
}
const text = await res.text().catch(() => "(no body)");
throw new Error(`POST /payments/${paymentId}/observe → HTTP ${res.status}: ${text}`);
}
throw new Error(`Observe for payment ${paymentId} did not settle after ${maxAttempts} attempts`);
}