forked from pot4e/FHE-contract-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinstance.ts
60 lines (51 loc) · 1.88 KB
/
instance.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
import { Signer } from "ethers";
import fhevmjs, { FhevmInstance } from "fhevmjs";
import { ethers as hethers } from "hardhat";
import { FHE_LIB_ADDRESS } from "./generated";
import type { Signers } from "./signers";
import { FhevmInstances } from "./types";
let publicKey: string;
let chainId: number;
export const createInstances = async (
contractAddress: string,
ethers: typeof hethers,
accounts: Signers,
): Promise<FhevmInstances> => {
if (!publicKey || !chainId) {
// 1. Get chain id
const provider = ethers.provider;
const network = await provider.getNetwork();
chainId = +network.chainId.toString(); // Need to be a number
// Get blockchain public key
const ret = await provider.call({
to: FHE_LIB_ADDRESS,
// first four bytes of keccak256('fhePubKey(bytes1)') + 1 byte for library
data: "0xd9d47bb001",
});
const decoded = ethers.AbiCoder.defaultAbiCoder().decode(["bytes"], ret);
publicKey = decoded[0];
}
// Create instance
const instances: FhevmInstances = {} as FhevmInstances;
await Promise.all(
Object.keys(accounts).map(async (k) => {
const instance = await fhevmjs.createInstance({ chainId, publicKey });
await generateToken(contractAddress, accounts[k as keyof Signers], instance);
instances[k as keyof FhevmInstances] = instance;
}),
);
return instances;
};
const generateToken = async (contractAddress: string, signer: Signer, instance: FhevmInstance) => {
// Generate token to decrypt
const generatedToken = instance.generatePublicKey({
verifyingContract: contractAddress,
});
// Sign the public key
const signature = await signer.signTypedData(
generatedToken.eip712.domain,
{ Reencrypt: generatedToken.eip712.types.Reencrypt }, // Need to remove EIP712Domain from types
generatedToken.eip712.message,
);
instance.setSignature(contractAddress, signature);
};