forked from LIT-Protocol/policy-AI-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagent-helpers.ts
171 lines (147 loc) Β· 4.9 KB
/
agent-helpers.ts
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
import { LitNodeClient } from "@lit-protocol/lit-node-client";
import { LIT_NETWORK } from "@lit-protocol/constants";
import { validateSessionSigs } from "@lit-protocol/misc";
import * as ethers from "ethers";
import { litActionCode } from "./LitActions/humanVerificationAction";
import { transactionActionCode } from "./LitActions/transactionAction";
import { getChainInfo, getPkpSessionSigs } from "./utils";
const LIT_PKP_PUBLIC_KEY = process.env.NEXT_PUBLIC_LIT_PKP_PUBLIC_KEY;
let litNodeClient: LitNodeClient | null = null;
let sessionSigs: any | null = null;
async function initializeLitClient() {
try {
if (litNodeClient && sessionSigs) {
return { litNodeClient, sessionSigs };
}
console.log("π Connecting to Lit network...");
litNodeClient = new LitNodeClient({
litNetwork: LIT_NETWORK.DatilDev,
debug: false,
});
await litNodeClient.connect();
console.log("β
Connected to Lit network");
sessionSigs = await getPkpSessionSigs(litNodeClient);
return { litNodeClient, sessionSigs };
} catch (error) {
console.error("Failed to initialize Lit client:", error);
litNodeClient = null;
sessionSigs = null;
throw error;
}
}
export async function humanVerification(amount: number) {
const { litNodeClient: client, sessionSigs: sigs } =
await initializeLitClient();
const isValid = validateSessionSigs({ sessionSigs: sigs });
if (!isValid) {
console.log("π Session signatures expired, refreshing...");
litNodeClient = null;
sessionSigs = null;
return await humanVerification(amount);
}
console.log("π Executing Lit Action for verification...");
const litActionResponse = await client.executeJs({
sessionSigs: sigs,
code: litActionCode,
jsParams: {
publicKey: LIT_PKP_PUBLIC_KEY!,
sigName: "sig",
amount: amount,
baseUrl: process.env.NEXT_PUBLIC_BASE_URL,
email: process.env.NEXT_PUBLIC_STYTCH_EMAIL,
},
});
console.log("β
Executed Lit Action");
if (litActionResponse.response !== "true") {
console.error("β Transaction process failed");
return false;
}
console.log("π§ Please check your email for verification");
return true;
}
export async function signAndBroadcastTransaction(
humanVerification: boolean,
txHash?: string,
amount?: number
) {
try {
let finalAmount: number;
if (humanVerification) {
const response = await fetch(`/api/database/fetch-transaction/${txHash}`);
const data = await response.json();
if (!data.success || !data.transaction) {
throw new Error("Failed to fetch transaction details");
}
finalAmount = data.transaction.amount;
} else {
if (amount === undefined) {
throw new Error(
"Amount must be provided when human verification is disabled"
);
}
finalAmount = amount;
}
const { litNodeClient: client, sessionSigs: sigs } =
await initializeLitClient();
const isValid = validateSessionSigs({ sessionSigs: sigs });
if (!isValid) {
console.log("π Session signatures expired, refreshing...");
litNodeClient = null;
sessionSigs = null;
return await signAndBroadcastTransaction(
humanVerification,
txHash,
amount
);
}
const chainInfo = getChainInfo("yellowstone");
const ethersProvider = new ethers.providers.JsonRpcProvider(
chainInfo.rpcUrl
);
const gasPrice = await ethersProvider.getGasPrice();
const unsignedTransaction = {
to: "0xa7D7BC15FCD782A5f2217d1Df20DFD14C1d218e9", // Arbitrary address
gasLimit: 21000,
gasPrice: gasPrice.toHexString(),
nonce: await ethersProvider.getTransactionCount(
ethers.utils.computeAddress(`0x${LIT_PKP_PUBLIC_KEY}`)
),
chainId: chainInfo.chainId,
value: ethers.utils
.parseUnits(finalAmount.toString(), "gwei")
.toHexString(),
};
const unsignedTransactionHash = ethers.utils.keccak256(
ethers.utils.serializeTransaction(unsignedTransaction)
);
const litActionResponse = await client.executeJs({
code: transactionActionCode,
jsParams: {
toSign: ethers.utils.arrayify(unsignedTransactionHash),
publicKey: LIT_PKP_PUBLIC_KEY!,
sigName: "signedtx",
chain: "yellowstone",
unsignedTransaction,
},
sessionSigs: sigs,
});
if (humanVerification) {
await fetch("/api/database/update-transaction", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
txHash: txHash,
status: "COMPLETED",
approved: true,
}),
});
}
console.log("Transaction completed with hash:", litActionResponse.response);
return litActionResponse.response;
} catch (error) {
console.error("Failed to sign and broadcast transaction:", error);
throw error;
}
}