diff --git a/.env.example b/.env.example index 45ca2b1e..2121c713 100644 --- a/.env.example +++ b/.env.example @@ -1,13 +1,18 @@ export INFURA_API_KEY="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" export MNEMONIC="adapt mosquito move limb mobile illegal tree voyage juice mosquito burger raise father hope layer" +export PRIVATE_KEY_FHEVM_DEPLOYER="0c66d8cde71d2faa29d0cb6e3a567d31279b6eace67b0a9d9ba869c119843a5e" export PRIVATE_KEY_GATEWAY_DEPLOYER="717fd99986df414889fd8b51069d4f90a50af72e542c58ee065f5883779099c6" export PRIVATE_KEY_GATEWAY_OWNER="717fd99986df414889fd8b51069d4f90a50af72e542c58ee065f5883779099c6" export PRIVATE_KEY_GATEWAY_RELAYER="7ec931411ad75a7c201469a385d6f18a325d4923f9f213bd882bbea87e160b67" export NUM_KMS_SIGNERS="1" -export PRIVATE_KEY_KMS_SIGNER_0="26698d458a21b843aa1ddbd5c5b098821ddf4218bb52498c4aad3a84849275bb" -export PRIVATE_KEY_KMS_SIGNER_1="e5b998ce1e664718772fa35e8d02b2b6a267a03a8ecadab15de5b125da7fa82b" -export PRIVATE_KEY_KMS_SIGNER_2="dca817bfe824b12c92d61e56056b956617da156bcd730379cb9203c822c9ba8e" -export PRIVATE_KEY_KMS_SIGNER_3="7ac1a2886ca07b3b7393ea5ff3613bb94d72129e2c7cbedc807eb55ff971394c" +export PRIVATE_KEY_KMS_SIGNER_0="388b7680e4e1afa06efbfd45cdd1fe39f3c6af381df6555a19661f283b97de91" +export PRIVATE_KEY_KMS_SIGNER_1="bbaed91514fa4b7c86aa4f73becbabcf4bce0ae130240f0d6ac3f87e06812440" +export PRIVATE_KEY_KMS_SIGNER_2="1bfa3e2233b0103ad67954a728b246c528916791f7fab4894ff361e3937b47e1" +export PRIVATE_KEY_KMS_SIGNER_3="7a604eed8cf4a43277d192aa0c7894d368577a4021e52bf45420f256e34c7dd7" +export ADDRESS_KMS_SIGNER_0="0x0971C80fF03B428fD2094dd5354600ab103201C5" +export ADDRESS_KMS_SIGNER_1="0xB68deCb047B5e6Cc82280502A7E2318c6b3E5eC6" +export ADDRESS_KMS_SIGNER_2="0xfe0fB0BCceb872ee7a6ef6c455e6E127Aef55DD7" +export ADDRESS_KMS_SIGNER_3="0x2dac5193bE0AB0eD8871399E6Ae61EAe6cc8cAE1" export PRIVATE_KEY_COPROCESSOR_ACCOUNT="7ec8ada6642fc4ccfb7729bc29c17cf8d21b61abd5642d1db992c0b8672ab901" export IS_COPROCESSOR="true" diff --git a/README.md b/README.md index cfa037f3..3979f927 100644 --- a/README.md +++ b/README.md @@ -253,23 +253,6 @@ npm run fhevm:start npm run fhevm:stop ``` -##### Faucet - -For development purposes, we provide a ready to use wallet. In order to use -it, prepare the .env file that contains the mnemonic. - -```bash -cp .env.example .env -``` - -This allows the developer to use a few accounts, each account can get coins: - -```bash -npm run fhevm:faucet:alice -npm run fhevm:faucet:bob -npm run fhevm:faucet:carol -``` - ##### Run test ```bash diff --git a/examples/Governor/Comp.sol b/examples/legacy/Governor/Comp.sol similarity index 99% rename from examples/Governor/Comp.sol rename to examples/legacy/Governor/Comp.sol index 69398611..fe14e7c6 100644 --- a/examples/Governor/Comp.sol +++ b/examples/legacy/Governor/Comp.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.24; -import "../../lib/TFHE.sol"; +import "../../../lib/TFHE.sol"; contract Comp { /// @notice EIP-20 token name for this token diff --git a/examples/Governor/GovernorZama.sol b/examples/legacy/Governor/GovernorZama.sol similarity index 99% rename from examples/Governor/GovernorZama.sol rename to examples/legacy/Governor/GovernorZama.sol index 1df13ed8..b4ed0936 100644 --- a/examples/Governor/GovernorZama.sol +++ b/examples/legacy/Governor/GovernorZama.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.24; -import "../../lib/TFHE.sol"; +import "../../../lib/TFHE.sol"; contract GovernorZama { /// @notice The name of this contract diff --git a/examples/Governor/SafeMath.sol b/examples/legacy/Governor/SafeMath.sol similarity index 100% rename from examples/Governor/SafeMath.sol rename to examples/legacy/Governor/SafeMath.sol diff --git a/examples/Governor/Timelock.sol b/examples/legacy/Governor/Timelock.sol similarity index 100% rename from examples/Governor/Timelock.sol rename to examples/legacy/Governor/Timelock.sol diff --git a/examples/Identity/CompliantERC20.sol b/examples/legacy/Identity/CompliantERC20.sol similarity index 95% rename from examples/Identity/CompliantERC20.sol rename to examples/legacy/Identity/CompliantERC20.sol index e9430a33..8ed53ee9 100644 --- a/examples/Identity/CompliantERC20.sol +++ b/examples/legacy/Identity/CompliantERC20.sol @@ -2,8 +2,8 @@ pragma solidity ^0.8.24; -import "../../lib/TFHE.sol"; -import "../EncryptedERC20.sol"; +import "../../../lib/TFHE.sol"; +import "../../EncryptedERC20.sol"; import "./ERC20Rules.sol"; import "./IdentityRegistry.sol"; diff --git a/examples/Identity/ERC20Rules.sol b/examples/legacy/Identity/ERC20Rules.sol similarity index 99% rename from examples/Identity/ERC20Rules.sol rename to examples/legacy/Identity/ERC20Rules.sol index 6dd04a49..cb394c24 100644 --- a/examples/Identity/ERC20Rules.sol +++ b/examples/legacy/Identity/ERC20Rules.sol @@ -2,7 +2,7 @@ pragma solidity ^0.8.24; -import "../../lib/TFHE.sol"; +import "../../../lib/TFHE.sol"; import "./IdentityRegistry.sol"; interface ICompliantERC20 { diff --git a/examples/Identity/IdentityRegistry.sol b/examples/legacy/Identity/IdentityRegistry.sol similarity index 99% rename from examples/Identity/IdentityRegistry.sol rename to examples/legacy/Identity/IdentityRegistry.sol index d8b2b9b5..656d84fa 100644 --- a/examples/Identity/IdentityRegistry.sol +++ b/examples/legacy/Identity/IdentityRegistry.sol @@ -6,7 +6,7 @@ import "@openzeppelin/contracts/access/Ownable2Step.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; -import "../../lib/TFHE.sol"; +import "../../../lib/TFHE.sol"; contract IdentityRegistry is Ownable2Step { uint constant MAX_IDENTIFIERS_LENGTH = 20; diff --git a/hardhat.config.ts b/hardhat.config.ts index 588f20a2..a90f1dbd 100644 --- a/hardhat.config.ts +++ b/hardhat.config.ts @@ -16,7 +16,6 @@ import './tasks/getEthereumAddress'; import './tasks/mint'; import './tasks/taskDeploy'; import './tasks/taskGatewayRelayer'; -import './tasks/taskIdentity'; import './tasks/taskTFHE'; extendProvider(async (provider, config, network) => { @@ -87,13 +86,14 @@ task('test', async (taskArgs, hre, runSuper) => { // Run modified test task if (hre.network.name === 'hardhat') { // in fhevm mode all this block is done when launching the node via `pnmp fhevm:start` - const privKeyDeployer = process.env.PRIVATE_KEY_GATEWAY_DEPLOYER; - await hre.run('task:computePredeployAddress', { privateKey: privKeyDeployer }); - await hre.run('task:computeACLAddress'); - await hre.run('task:computeTFHEExecutorAddress'); - await hre.run('task:computeKMSVerifierAddress'); - await hre.run('task:computeInputVerifierAddress'); - await hre.run('task:computeFHEPaymentAddress'); + const privKeyGatewayDeployer = process.env.PRIVATE_KEY_GATEWAY_DEPLOYER; + const privKeyFhevmDeployer = process.env.PRIVATE_KEY_FHEVM_DEPLOYER; + await hre.run('task:computeGatewayAddress', { privateKey: privKeyGatewayDeployer }); + await hre.run('task:computeACLAddress', { privateKey: privKeyFhevmDeployer }); + await hre.run('task:computeTFHEExecutorAddress', { privateKey: privKeyFhevmDeployer }); + await hre.run('task:computeKMSVerifierAddress', { privateKey: privKeyFhevmDeployer }); + await hre.run('task:computeInputVerifierAddress', { privateKey: privKeyFhevmDeployer }); + await hre.run('task:computeFHEPaymentAddress', { privateKey: privKeyFhevmDeployer }); if (process.env.IS_COPROCESSOR === 'true') { await fs.copyFile('lib/InputVerifier.sol.coprocessor', 'lib/InputVerifier.sol'); } else { @@ -102,12 +102,17 @@ task('test', async (taskArgs, hre, runSuper) => { await hre.run('compile:specific', { contract: 'lib' }); await hre.run('compile:specific', { contract: 'gateway' }); await hre.run('compile:specific', { contract: 'payment' }); - await hre.run('task:deployACL'); - await hre.run('task:deployTFHEExecutor'); - await hre.run('task:deployKMSVerifier'); - await hre.run('task:deployInputVerifier'); - await hre.run('task:deployFHEPayment'); - await hre.run('task:addSigners', { numSigners: +process.env.NUM_KMS_SIGNERS! }); + await hre.run('task:faucetToPrivate', { privateKey: privKeyFhevmDeployer }); + await hre.run('task:deployACL', { privateKey: privKeyFhevmDeployer }); + await hre.run('task:deployTFHEExecutor', { privateKey: privKeyFhevmDeployer }); + await hre.run('task:deployKMSVerifier', { privateKey: privKeyFhevmDeployer }); + await hre.run('task:deployInputVerifier', { privateKey: privKeyFhevmDeployer }); + await hre.run('task:deployFHEPayment', { privateKey: privKeyFhevmDeployer }); + await hre.run('task:addSigners', { + numSigners: +process.env.NUM_KMS_SIGNERS!, + privateKey: privKeyFhevmDeployer, + useAddress: false, + }); await hre.run('task:launchFhevm', { skipGetCoin: false }); } await hre.run('compile:specific', { contract: 'examples' }); diff --git a/launch-fhevm.sh b/launch-fhevm.sh index dc0c1403..847b0958 100755 --- a/launch-fhevm.sh +++ b/launch-fhevm.sh @@ -1,33 +1,34 @@ #!/bin/bash +npx hardhat clean PRIVATE_KEY_GATEWAY_DEPLOYER=$(grep PRIVATE_KEY_GATEWAY_DEPLOYER .env | cut -d '"' -f 2) - -npx hardhat task:computePredeployAddress --private-key "$PRIVATE_KEY_GATEWAY_DEPLOYER" - -PRIVATE_KEY_GATEWAY_RELAYER=$(grep PRIVATE_KEY_GATEWAY_RELAYER .env | cut -d '"' -f 2) - -GATEWAY_CONTRACT_PREDEPLOY_ADDRESS=$(grep GATEWAY_CONTRACT_PREDEPLOY_ADDRESS gateway/.env.gateway | cut -d '=' -f2) - -TFHE_EXECUTOR_CONTRACT_ADDRESS=$(grep TFHE_EXECUTOR_CONTRACT_ADDRESS lib/.env.exec | cut -d '=' -f2) - -docker run -d -i -p 8545:8545 --rm --name fhevm \ - -e PRIVATE_KEY_ORACLE_RELAYER="$PRIVATE_KEY_ORACLE_RELAYER" \ - -e ORACLE_CONTRACT_PREDEPLOY_ADDRESS="$ORACLE_CONTRACT_PREDEPLOY_ADDRESS" \ - -e TFHE_EXECUTOR_CONTRACT_ADDRESS="$TFHE_EXECUTOR_CONTRACT_ADDRESS" \ - ghcr.io/zama-ai/ethermint-dev-node:v0.5.0-1 - -sleep 10 - -npx hardhat task:computeACLAddress -npx hardhat task:computeTFHEExecutorAddress -npx hardhat task:computeKMSVerifierAddress -npx hardhat task:deployACL -npx hardhat task:deployTFHEExecutor -npx hardhat task:deployKMSVerifier - +PRIVATE_KEY_FHEVM_DEPLOYER=$(grep PRIVATE_KEY_FHEVM_DEPLOYER .env | cut -d '"' -f 2) +NUM_KMS_SIGNERS=$(grep NUM_KMS_SIGNERS .env | cut -d '"' -f 2) +IS_COPROCESSOR=$(grep IS_COPROCESSOR .env | cut -d '"' -f 2) + +npx hardhat task:computeGatewayAddress --private-key "$PRIVATE_KEY_GATEWAY_DEPLOYER" +npx hardhat task:computeACLAddress --private-key "$PRIVATE_KEY_FHEVM_DEPLOYER" +npx hardhat task:computeTFHEExecutorAddress --private-key "$PRIVATE_KEY_FHEVM_DEPLOYER" +npx hardhat task:computeKMSVerifierAddress --private-key "$PRIVATE_KEY_FHEVM_DEPLOYER" +npx hardhat task:computeInputVerifierAddress --private-key "$PRIVATE_KEY_FHEVM_DEPLOYER" +npx hardhat task:computeFHEPaymentAddress --private-key "$PRIVATE_KEY_FHEVM_DEPLOYER" + +# [ADD DOCKER-COMPOSE COMMAND HERE] // Geth node, Gateway service, KMS service etc should be launched here, using previously precomputed addresses + +if [ "$IS_COPROCESSOR" = "true" ]; then + cp lib/InputVerifier.sol.coprocessor lib/InputVerifier.sol +else + cp lib/InputVerifier.sol.native lib/InputVerifier.sol +fi npx hardhat compile:specific --contract lib npx hardhat compile:specific --contract gateway -npx hardhat task:launchFhevm +npx hardhat task:deployACL --private-key "$PRIVATE_KEY_FHEVM_DEPLOYER" +npx hardhat task:deployTFHEExecutor --private-key "$PRIVATE_KEY_FHEVM_DEPLOYER" +npx hardhat task:deployKMSVerifier --private-key "$PRIVATE_KEY_FHEVM_DEPLOYER" +npx hardhat task:deployInputVerifier --private-key "$PRIVATE_KEY_FHEVM_DEPLOYER" +npx hardhat task:deployFHEPayment --private-key "$PRIVATE_KEY_FHEVM_DEPLOYER" + +npx hardhat task:addSigners --num-signers $NUM_KMS_SIGNERS --private-key "$PRIVATE_KEY_FHEVM_DEPLOYER" --useAddress true -docker attach fhevm +npx hardhat task:launchFhevm --skip-get-coin true \ No newline at end of file diff --git a/lib/.env.acl b/lib/.env.acl index adc70118..83c07ff7 100644 --- a/lib/.env.acl +++ b/lib/.env.acl @@ -1 +1 @@ -ACL_CONTRACT_ADDRESS=0x05fD9B5EFE0a996095f42Ed7e77c390810CF660c +ACL_CONTRACT_ADDRESS=0x339EcE85B9E11a3A3AA557582784a15d7F82AAf2 diff --git a/lib/.env.exec b/lib/.env.exec index b0bb5d23..adba3fce 100644 --- a/lib/.env.exec +++ b/lib/.env.exec @@ -1 +1 @@ -TFHE_EXECUTOR_CONTRACT_ADDRESS=0xcCAe95fF1d11656358E782570dF0418F59fA40e1 +TFHE_EXECUTOR_CONTRACT_ADDRESS=0x596E6682c72946AF006B27C131793F2b62527A4b diff --git a/lib/.env.fhepayment b/lib/.env.fhepayment index faf1f126..2a38d176 100644 --- a/lib/.env.fhepayment +++ b/lib/.env.fhepayment @@ -1 +1 @@ -FHE_PAYMENT_CONTRACT_ADDRESS=0x222ea0147FF597Ff1935B2a55afeDC404425203d +FHE_PAYMENT_CONTRACT_ADDRESS=0x6d5A11aC509C707c00bc3A0a113ACcC26c532547 diff --git a/lib/.env.inputverifier b/lib/.env.inputverifier index f95b2da3..b628bb02 100644 --- a/lib/.env.inputverifier +++ b/lib/.env.inputverifier @@ -1 +1 @@ -INPUT_VERIFIER_CONTRACT_ADDRESS=0x52054F36036811ca418be59e41Fc6DD1b9e4F4c8 +INPUT_VERIFIER_CONTRACT_ADDRESS=0x69dE3158643e738a0724418b21a35FAA20CBb1c5 diff --git a/lib/.env.kmsverifier b/lib/.env.kmsverifier index 23871484..d5db2185 100644 --- a/lib/.env.kmsverifier +++ b/lib/.env.kmsverifier @@ -1 +1 @@ -KMS_VERIFIER_CONTRACT_ADDRESS=0x857Ca72A957920Fa0FB138602995839866Bd4005 +KMS_VERIFIER_CONTRACT_ADDRESS=0x208De73316E44722e16f6dDFF40881A3e4F86104 diff --git a/lib/ACLAddress.sol b/lib/ACLAddress.sol index 2052f317..06488813 100644 --- a/lib/ACLAddress.sol +++ b/lib/ACLAddress.sol @@ -2,4 +2,4 @@ pragma solidity ^0.8.24; -address constant aclAdd = 0x05fD9B5EFE0a996095f42Ed7e77c390810CF660c; +address constant aclAdd = 0x339EcE85B9E11a3A3AA557582784a15d7F82AAf2; diff --git a/lib/FHEPaymentAddress.sol b/lib/FHEPaymentAddress.sol index 4a9c735f..8b0e4358 100644 --- a/lib/FHEPaymentAddress.sol +++ b/lib/FHEPaymentAddress.sol @@ -2,4 +2,4 @@ pragma solidity ^0.8.24; -address constant fhePaymentAdd = 0x222ea0147FF597Ff1935B2a55afeDC404425203d; +address constant fhePaymentAdd = 0x6d5A11aC509C707c00bc3A0a113ACcC26c532547; diff --git a/lib/InputVerifierAddress.sol b/lib/InputVerifierAddress.sol index 4c3f4cc2..6dfb7606 100644 --- a/lib/InputVerifierAddress.sol +++ b/lib/InputVerifierAddress.sol @@ -2,4 +2,4 @@ pragma solidity ^0.8.24; -address constant inputVerifierAdd = 0x52054F36036811ca418be59e41Fc6DD1b9e4F4c8; +address constant inputVerifierAdd = 0x69dE3158643e738a0724418b21a35FAA20CBb1c5; diff --git a/lib/KMSVerifierAddress.sol b/lib/KMSVerifierAddress.sol index 34443a5e..e9293d6b 100644 --- a/lib/KMSVerifierAddress.sol +++ b/lib/KMSVerifierAddress.sol @@ -2,4 +2,4 @@ pragma solidity ^0.8.24; -address constant kmsVerifierAdd = 0x857Ca72A957920Fa0FB138602995839866Bd4005; +address constant kmsVerifierAdd = 0x208De73316E44722e16f6dDFF40881A3e4F86104; diff --git a/lib/TFHEExecutorAddress.sol b/lib/TFHEExecutorAddress.sol index 64d75675..f13f3da8 100644 --- a/lib/TFHEExecutorAddress.sol +++ b/lib/TFHEExecutorAddress.sol @@ -2,4 +2,4 @@ pragma solidity ^0.8.24; -address constant tfheExecutorAdd = 0xcCAe95fF1d11656358E782570dF0418F59fA40e1; +address constant tfheExecutorAdd = 0x596E6682c72946AF006B27C131793F2b62527A4b; diff --git a/package.json b/package.json index be3cdeff..ead155f0 100644 --- a/package.json +++ b/package.json @@ -26,19 +26,12 @@ "codegen": "npx ts-node codegen/main.ts && npm run prettier", "codegen:overloads": "npx ts-node codegen/generateOverloads.ts", "task:getEthereumAddress": "hardhat task:getEthereumAddress", - "task:deployIdentity": "hardhat task:deployIdentity", "task:deployGateway": "hardhat task:deployGateway", "task:addRelayer": "hardhat task:addRelayer", "task:removeRelayer": "hardhat task:removeRelayer", "fhevm:start": " ./launch-fhevm.sh", "fhevm:stop": "docker rm -f fhevm", - "fhevm:restart": "fhevm:stop && fhevm:start", - "fhevm:faucet": "npm run fhevm:faucet:alice && sleep 5 && npm run fhevm:faucet:bob && sleep 5 && npm run fhevm:faucet:carol && sleep 5 && npm run fhevm:faucet:dave && sleep 5 && npm run fhevm:faucet:eve", - "fhevm:faucet:alice": "docker exec -i fhevm faucet $(npx hardhat task:getEthereumAddressAlice)", - "fhevm:faucet:bob": "docker exec -i fhevm faucet $(npx hardhat task:getEthereumAddressBob)", - "fhevm:faucet:carol": "docker exec -i fhevm faucet $(npx hardhat task:getEthereumAddressCarol)", - "fhevm:faucet:dave": "docker exec -i fhevm faucet $(npx hardhat task:getEthereumAddressDave)", - "fhevm:faucet:eve": "docker exec -i fhevm faucet $(npx hardhat task:getEthereumAddressEve)" + "fhevm:restart": "fhevm:stop && fhevm:start" }, "repository": { "type": "git", diff --git a/setup-local-fhevm.sh b/setup-local-fhevm.sh deleted file mode 100755 index f568a3d2..00000000 --- a/setup-local-fhevm.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash - -# Assumes the following: -# 1. A local and **fresh** fhEVM node is already running. -# 2. All test addresses are funded (e.g. via the fund_test_addresses.sh script). -npx hardhat clean -npx hardhat compile:specific --contract lib -npx hardhat compile:specific --contract gateway - -PRIVATE_KEY_GATEWAY_DEPLOYER=$(grep PRIVATE_KEY_GATEWAY_DEPLOYER .env | cut -d '"' -f 2) -npx hardhat task:computePredeployAddress --private-key "$PRIVATE_KEY_GATEWAY_DEPLOYER" - -npx hardhat task:computeACLAddress -npx hardhat task:computeTFHEExecutorAddress -npx hardhat task:computeKMSVerifierAddress -npx hardhat task:deployACL -npx hardhat task:deployTFHEExecutor -npx hardhat task:deployKMSVerifier - -npx hardhat task:launchFhevm --skip-get-coin true diff --git a/tasks/mint.ts b/tasks/mint.ts index a8c68dcd..862376c6 100644 --- a/tasks/mint.ts +++ b/tasks/mint.ts @@ -1,6 +1,14 @@ import { task } from 'hardhat/config'; import type { TaskArguments } from 'hardhat/types'; +task('task:deployERC20').setAction(async function (taskArguments: TaskArguments, { ethers }) { + const signers = await ethers.getSigners(); + const erc20Factory = await ethers.getContractFactory('EncryptedERC20'); + const encryptedERC20 = await erc20Factory.connect(signers[0]).deploy('Naraggara', 'NARA'); + await encryptedERC20.waitForDeployment(); + console.log('EncryptedERC20 deployed to: ', await encryptedERC20.getAddress()); +}); + task('task:mint') .addParam('mint', 'Tokens to mint') .setAction(async function (taskArguments: TaskArguments, hre) { diff --git a/tasks/taskDeploy.ts b/tasks/taskDeploy.ts index 771e7854..9365f400 100644 --- a/tasks/taskDeploy.ts +++ b/tasks/taskDeploy.ts @@ -1,17 +1,8 @@ -import chalk from 'chalk'; import dotenv from 'dotenv'; import fs from 'fs'; import { task } from 'hardhat/config'; import type { TaskArguments } from 'hardhat/types'; -task('task:deployERC20').setAction(async function (taskArguments: TaskArguments, { ethers }) { - const signers = await ethers.getSigners(); - const erc20Factory = await ethers.getContractFactory('EncryptedERC20'); - const encryptedERC20 = await erc20Factory.connect(signers[0]).deploy('Naraggara', 'NARA'); - await encryptedERC20.waitForDeployment(); - console.log('EncryptedERC20 deployed to: ', await encryptedERC20.getAddress()); -}); - task('task:deployGateway') .addParam('privateKey', 'The deployer private key') .addParam('ownerAddress', 'The owner address') @@ -33,109 +24,120 @@ task('task:deployGateway') console.log('GatewayContract was deployed at address: ', GatewayContractAddress); }); -task('task:deployIdentity').setAction(async function (taskArguments: TaskArguments, { ethers }) { - const signers = await ethers.getSigners(); - - const identityRegistryFactory = await ethers.getContractFactory('IdentityRegistry'); - const identityRegistry = await identityRegistryFactory.connect(signers[0]).deploy(); - - const erc20RulesFactory = await ethers.getContractFactory('ERC20Rules'); - const erc20Rules = await erc20RulesFactory.connect(signers[0]).deploy(); - await identityRegistry.waitForDeployment(); - await erc20Rules.waitForDeployment(); - - const compliantERC20Factory = await ethers.getContractFactory('CompliantERC20'); - const compliantERC20 = await compliantERC20Factory - .connect(signers[0]) - .deploy(await identityRegistry.getAddress(), await erc20Rules.getAddress(), 'CompliantToken', 'CTOK'); - await compliantERC20.waitForDeployment(); - - const registryAddress = await identityRegistry.getAddress(); - const erc20Address = await compliantERC20.getAddress(); - console.log(chalk.bold('Available methods:')); - console.log(`npx hardhat task:identity:initRegistry --registry ${registryAddress}`); - console.log(`npx hardhat task:identity:grantAccess --registry ${registryAddress} --erc20 ${erc20Address}`); - console.log(`npx hardhat task:identity:mint --erc20 ${erc20Address}`); - console.log(`npx hardhat task:identity:transfer --erc20 ${erc20Address} --from carol --to dave --amount 2000`); - console.log(`npx hardhat task:identity:balanceOf --erc20 ${erc20Address} --user alice`); -}); - -task('task:deployACL').setAction(async function (taskArguments: TaskArguments, { ethers, upgrades }) { - const deployer = (await ethers.getSigners())[9]; - const factory = await ethers.getContractFactory('ACL', deployer); - const acl = await upgrades.deployProxy(factory, [deployer.address], { initializer: 'initialize', kind: 'uups' }); - await acl.waitForDeployment(); - const address = await acl.getAddress(); - const envConfigAcl = dotenv.parse(fs.readFileSync('lib/.env.acl')); - if (address !== envConfigAcl.ACL_CONTRACT_ADDRESS) { - throw new Error(`The nonce of the deployer account is not correct. Please relaunch a clean instance of the fhEVM`); - } - console.log('ACL was deployed at address:', address); -}); +task('task:deployACL') + .addParam('privateKey', 'The deployer private key') + .setAction(async function (taskArguments: TaskArguments, { ethers, upgrades }) { + const deployer = new ethers.Wallet(taskArguments.privateKey).connect(ethers.provider); + const factory = await ethers.getContractFactory('ACL', deployer); + const acl = await upgrades.deployProxy(factory, [deployer.address], { initializer: 'initialize', kind: 'uups' }); + await acl.waitForDeployment(); + const address = await acl.getAddress(); + const envConfigAcl = dotenv.parse(fs.readFileSync('lib/.env.acl')); + if (address !== envConfigAcl.ACL_CONTRACT_ADDRESS) { + throw new Error( + `The nonce of the deployer account is not correct. Please relaunch a clean instance of the fhEVM`, + ); + } + console.log('ACL was deployed at address:', address); + }); -task('task:deployTFHEExecutor').setAction(async function (taskArguments: TaskArguments, { ethers, upgrades }) { - const deployer = (await ethers.getSigners())[9]; - const factory = await ethers.getContractFactory('TFHEExecutor', deployer); - const exec = await upgrades.deployProxy(factory, [deployer.address], { initializer: 'initialize', kind: 'uups' }); - await exec.waitForDeployment(); - const address = await exec.getAddress(); - const envConfig = dotenv.parse(fs.readFileSync('lib/.env.exec')); - if (address !== envConfig.TFHE_EXECUTOR_CONTRACT_ADDRESS) { - throw new Error(`The nonce of the deployer account is not correct. Please relaunch a clean instance of the fhEVM`); - } - console.log('TFHEExecutor was deployed at address:', address); -}); +task('task:deployTFHEExecutor') + .addParam('privateKey', 'The deployer private key') + .setAction(async function (taskArguments: TaskArguments, { ethers, upgrades }) { + const deployer = new ethers.Wallet(taskArguments.privateKey).connect(ethers.provider); + const factory = await ethers.getContractFactory('TFHEExecutor', deployer); + const exec = await upgrades.deployProxy(factory, [deployer.address], { initializer: 'initialize', kind: 'uups' }); + await exec.waitForDeployment(); + const address = await exec.getAddress(); + const envConfig = dotenv.parse(fs.readFileSync('lib/.env.exec')); + if (address !== envConfig.TFHE_EXECUTOR_CONTRACT_ADDRESS) { + throw new Error( + `The nonce of the deployer account is not correct. Please relaunch a clean instance of the fhEVM`, + ); + } + console.log('TFHEExecutor was deployed at address:', address); + }); -task('task:deployKMSVerifier').setAction(async function (taskArguments: TaskArguments, { ethers, upgrades }) { - const deployer = (await ethers.getSigners())[9]; - const factory = await ethers.getContractFactory('KMSVerifier', deployer); - const kms = await upgrades.deployProxy(factory, [deployer.address], { initializer: 'initialize', kind: 'uups' }); - await kms.waitForDeployment(); - const address = await kms.getAddress(); - const envConfig = dotenv.parse(fs.readFileSync('lib/.env.kmsverifier')); - if (address !== envConfig.KMS_VERIFIER_CONTRACT_ADDRESS) { - throw new Error(`The nonce of the deployer account is not correct. Please relaunch a clean instance of the fhEVM`); - } - console.log('KMSVerifier was deployed at address:', address); -}); +task('task:deployKMSVerifier') + .addParam('privateKey', 'The deployer private key') + .setAction(async function (taskArguments: TaskArguments, { ethers, upgrades }) { + const deployer = new ethers.Wallet(taskArguments.privateKey).connect(ethers.provider); + const factory = await ethers.getContractFactory('KMSVerifier', deployer); + const kms = await upgrades.deployProxy(factory, [deployer.address], { initializer: 'initialize', kind: 'uups' }); + await kms.waitForDeployment(); + const address = await kms.getAddress(); + const envConfig = dotenv.parse(fs.readFileSync('lib/.env.kmsverifier')); + if (address !== envConfig.KMS_VERIFIER_CONTRACT_ADDRESS) { + throw new Error( + `The nonce of the deployer account is not correct. Please relaunch a clean instance of the fhEVM`, + ); + } + console.log('KMSVerifier was deployed at address:', address); + }); -task('task:deployInputVerifier').setAction(async function (taskArguments: TaskArguments, { ethers, upgrades }) { - const deployer = (await ethers.getSigners())[9]; - const factory = await ethers.getContractFactory('InputVerifier', deployer); - const kms = await upgrades.deployProxy(factory, [deployer.address], { initializer: 'initialize', kind: 'uups' }); - await kms.waitForDeployment(); - const address = await kms.getAddress(); - const envConfig = dotenv.parse(fs.readFileSync('lib/.env.inputverifier')); - if (address !== envConfig.INPUT_VERIFIER_CONTRACT_ADDRESS) { - throw new Error(`The nonce of the deployer account is not correct. Please relaunch a clean instance of the fhEVM`); - } - console.log('InputVerifier was deployed at address:', address); -}); +task('task:deployInputVerifier') + .addParam('privateKey', 'The deployer private key') + .setAction(async function (taskArguments: TaskArguments, { ethers, upgrades }) { + const deployer = new ethers.Wallet(taskArguments.privateKey).connect(ethers.provider); + const factory = await ethers.getContractFactory('InputVerifier', deployer); + const kms = await upgrades.deployProxy(factory, [deployer.address], { initializer: 'initialize', kind: 'uups' }); + await kms.waitForDeployment(); + const address = await kms.getAddress(); + const envConfig = dotenv.parse(fs.readFileSync('lib/.env.inputverifier')); + if (address !== envConfig.INPUT_VERIFIER_CONTRACT_ADDRESS) { + throw new Error( + `The nonce of the deployer account is not correct. Please relaunch a clean instance of the fhEVM`, + ); + } + console.log('InputVerifier was deployed at address:', address); + }); -task('task:deployFHEPayment').setAction(async function (taskArguments: TaskArguments, { ethers, upgrades }) { - const deployer = (await ethers.getSigners())[9]; - const factory = await ethers.getContractFactory('FHEPayment', deployer); - const payment = await upgrades.deployProxy(factory, [deployer.address], { initializer: 'initialize', kind: 'uups' }); - await payment.waitForDeployment(); - const address = await payment.getAddress(); - const envConfig = dotenv.parse(fs.readFileSync('lib/.env.fhepayment')); - if (address !== envConfig.FHE_PAYMENT_CONTRACT_ADDRESS) { - throw new Error(`The nonce of the deployer account is not correct. Please relaunch a clean instance of the fhEVM`); - } - console.log('FHEPayment was deployed at address:', address); -}); +task('task:deployFHEPayment') + .addParam('privateKey', 'The deployer private key') + .setAction(async function (taskArguments: TaskArguments, { ethers, upgrades }) { + const deployer = new ethers.Wallet(taskArguments.privateKey).connect(ethers.provider); + const factory = await ethers.getContractFactory('FHEPayment', deployer); + const payment = await upgrades.deployProxy(factory, [deployer.address], { + initializer: 'initialize', + kind: 'uups', + }); + await payment.waitForDeployment(); + const address = await payment.getAddress(); + const envConfig = dotenv.parse(fs.readFileSync('lib/.env.fhepayment')); + if (address !== envConfig.FHE_PAYMENT_CONTRACT_ADDRESS) { + throw new Error( + `The nonce of the deployer account is not correct. Please relaunch a clean instance of the fhEVM`, + ); + } + console.log('FHEPayment was deployed at address:', address); + }); -task('task:addSigners').setAction(async function (taskArguments: TaskArguments, { ethers }) { - const deployer = (await ethers.getSigners())[9]; - const factory = await ethers.getContractFactory('KMSVerifier', deployer); - const kmsAdd = dotenv.parse(fs.readFileSync('lib/.env.kmsverifier')).KMS_VERIFIER_CONTRACT_ADDRESS; - const kmsVerifier = await factory.attach(kmsAdd); +task('task:addSigners') + .addParam('privateKey', 'The deployer private key') + .addOptionalParam( + 'useAddress', + 'Use addresses instead of private keys env variables for kms signers', + false, + types.boolean, + ) + .setAction(async function (taskArguments: TaskArguments, { ethers }) { + const deployer = new ethers.Wallet(taskArguments.privateKey).connect(ethers.provider); + const factory = await ethers.getContractFactory('KMSVerifier', deployer); + const kmsAdd = dotenv.parse(fs.readFileSync('lib/.env.kmsverifier')).KMS_VERIFIER_CONTRACT_ADDRESS; + const kmsVerifier = await factory.attach(kmsAdd); - for (let idx = 0; idx < taskArguments.numSigners; idx++) { - const privKeySigner = process.env[`PRIVATE_KEY_KMS_SIGNER_${idx}`]; - const kmsSigner = new ethers.Wallet(privKeySigner).connect(ethers.provider); - const tx = await kmsVerifier.addSigner(kmsSigner.address); - await tx.wait(); - console.log(`KMS signer no${idx} (${kmsSigner.address}) was added to KMSVerifier contract`); - } -}); + for (let idx = 0; idx < taskArguments.numSigners; idx++) { + if (!taskArguments.useAddress) { + const privKeySigner = process.env[`PRIVATE_KEY_KMS_SIGNER_${idx}`]; + const kmsSigner = new ethers.Wallet(privKeySigner).connect(ethers.provider); + const tx = await kmsVerifier.addSigner(kmsSigner.address); + await tx.wait(); + console.log(`KMS signer no${idx} (${kmsSigner.address}) was added to KMSVerifier contract`); + } else { + const kmsSignerAddress = process.env[`ADDRESS_KMS_SIGNER_${idx}`]; + const tx = await kmsVerifier.addSigner(kmsSignerAddress); + await tx.wait(); + console.log(`KMS signer no${idx} (${kmsSignerAddress}) was added to KMSVerifier contract`); + } + } + }); diff --git a/tasks/taskGatewayRelayer.ts b/tasks/taskGatewayRelayer.ts index 945024f3..476efbd4 100644 --- a/tasks/taskGatewayRelayer.ts +++ b/tasks/taskGatewayRelayer.ts @@ -15,7 +15,7 @@ const getCoin = async (address: string) => { if (res.raw_log.match('account sequence mismatch')) await getCoin(address); }; -task('task:computePredeployAddress') +task('task:computeGatewayAddress') .addParam('privateKey', 'The deployer private key') .setAction(async function (taskArguments: TaskArguments, { ethers }) { const deployerAddress = new ethers.Wallet(taskArguments.privateKey).address; @@ -136,3 +136,31 @@ task('task:getBalances').setAction(async function (taskArgs, hre) { console.log(await hre.ethers.provider.getBalance(ownerAddress)); console.log(await hre.ethers.provider.getBalance(relayerAddress)); }); + +task('task:faucetToPrivate') + .addParam('privateKey', 'The receiver private key') + .setAction(async function (taskArgs, hre) { + const receiverAddress = new hre.ethers.Wallet(taskArgs.privateKey).address; + + if (hre.network.name === 'hardhat') { + const bal = '0x1000000000000000000000000000000000000000'; + await hre.network.provider.send('hardhat_setBalance', [receiverAddress, bal]); + } else { + await getCoin(receiverAddress); + await new Promise((res) => setTimeout(res, 5000)); // wait 5 seconds + } + }); + +task('task:faucetToAddress') + .addParam('address', 'The receiver address') + .setAction(async function (taskArgs, hre) { + const receiverAddress = taskArgs.address; + + if (hre.network.name === 'hardhat') { + const bal = '0x1000000000000000000000000000000000000000'; + await hre.network.provider.send('hardhat_setBalance', [receiverAddress, bal]); + } else { + await getCoin(receiverAddress); + await new Promise((res) => setTimeout(res, 5000)); // wait 5 seconds + } + }); diff --git a/tasks/taskIdentity.ts b/tasks/taskIdentity.ts deleted file mode 100644 index 3e57ed74..00000000 --- a/tasks/taskIdentity.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { SignerWithAddress } from '@nomicfoundation/hardhat-ethers/signers'; -import chalk from 'chalk'; -import { task } from 'hardhat/config'; -import type { TaskArguments } from 'hardhat/types'; - -import { createInstance } from './utils'; - -const getSigners = (eSigners: SignerWithAddress[]) => ({ - alice: eSigners[0], - bob: eSigners[1], - carol: eSigners[2], - dave: eSigners[3], -}); - -task('task:identity:initRegistry') - .addParam('registry', 'Registry contract address') - .setAction(async function (taskArguments: TaskArguments, { ethers }) { - const contractAddress = taskArguments.registry; - - const signers = await ethers.getSigners(); - const contract = (await ethers.getContractAt('IdentityRegistry', contractAddress)).connect(signers[0]) as any; - console.log(chalk.bold('Step 1: Adding registrar')); - console.log(chalk.italic('eg: registry.addRegistrar(wallet, id)')); - try { - const addRegistrarTx = await contract.addRegistrar(signers[1], 1); - await addRegistrarTx.wait(); - console.log("=> Bob is a registrar with registrar id '1'"); - } catch (e) { - console.log('=> Bob is already a registrar'); - } - - console.log('---'); - console.log(chalk.bold('Step 2: Adding decentralized id for 4 users (Alice, Bob, Carol and Dave)')); - console.log(chalk.italic('eg: registry.addDid(wallet)')); - try { - const tx1 = await contract.connect(signers[1]).addDid(signers[0]); - const tx2 = await contract.connect(signers[1]).addDid(signers[1]); - const tx3 = await contract.connect(signers[1]).addDid(signers[2]); - const tx4 = await contract.connect(signers[1]).addDid(signers[3]); - await Promise.all([tx1.wait(), tx2.wait(), tx3.wait(), tx4.wait()]); - console.log('=> Did added for Alice, Bob, Carol and Dave'); - } catch (e) { - console.log('=> Did was already added'); - } - - console.log('---'); - - console.log(chalk.bold('Step 3: Adding country identifiers')); - console.log(chalk.italic("eg: registry.setIdentifier(wallet, 'country', Enc(1))")); - const instance = await createInstance(contractAddress, signers[0], ethers); - - const country1 = instance.encrypt64(1); - const country2 = instance.encrypt64(2); - - const tx1Identifier = await contract.connect(signers[1]).setIdentifier(signers[0], 'country', country1); - const tx2Identifier = await contract.connect(signers[1]).setIdentifier(signers[1], 'country', country1); - const tx3Identifier = await contract.connect(signers[1]).setIdentifier(signers[2], 'country', country1); - const tx4Identifier = await contract.connect(signers[1]).setIdentifier(signers[3], 'country', country2); - await Promise.all([tx1Identifier.wait(), tx2Identifier.wait(), tx3Identifier.wait(), tx4Identifier.wait()]); - console.log("=> Alice, Bob and Carol are from country '1'"); - console.log("=> Dave is from country '2'"); - }); - -task('task:identity:grantAccess') - .addParam('registry', 'Registry contract address') - .addParam('erc20', 'ERC20 contract address') - .setAction(async function (taskArguments: TaskArguments, { ethers }) { - const registryAddress = taskArguments.registry; - const erc20Address = taskArguments.erc20; - - const signers = await ethers.getSigners(); - const registry = (await ethers.getContractAt('IdentityRegistry', registryAddress)) as any; - const erc20 = await ethers.getContractAt('CompliantERC20', erc20Address); - - console.log(chalk.bold('Step 1: Getting list of identifiers from ERC20 contract')); - console.log(chalk.italic('eg: erc20.identifiers()')); - const identifiers = [...(await erc20.identifiers())]; - console.log('=> List of identifiers needed:', identifiers); - - console.log('---'); - - console.log(chalk.bold('Step 2: Grant access to the ERC20 contract to these identifiers')); - console.log(chalk.italic("eg: erc20.grantAccess(erc20Address, ['country', 'blacklist'])")); - const txs = await Promise.all([ - registry.connect(signers[0]).grantAccess(erc20Address, identifiers), - registry.connect(signers[1]).grantAccess(erc20Address, identifiers), - registry.connect(signers[2]).grantAccess(erc20Address, identifiers), - registry.connect(signers[3]).grantAccess(erc20Address, identifiers), - ]); - await Promise.all(txs.map((tx) => tx.wait())); - console.log('=> Access granted to the ERC20 contract for all users.'); - }); - -task('task:identity:mint') - .addParam('erc20', 'ERC20 contract address') - .setAction(async function (taskArguments: TaskArguments, { ethers }) { - const erc20Address = taskArguments.erc20; - - const signers = await ethers.getSigners(); - const erc20 = await ethers.getContractAt('CompliantERC20', erc20Address); - - const instance = await createInstance(erc20Address, signers[0], ethers); - - console.log(chalk.bold('Step 1: Alice mints 100 000 tokens on the compliant contract')); - console.log(chalk.italic('eg: erc20.mint(Enc(100000))')); - const transaction = await erc20.mint(100000); - await transaction.wait(); - console.log('=> 10000 tokens have been minted'); - - console.log('---'); - - console.log(chalk.bold('Step 2: Alice transfers some tokens')); - console.log(chalk.italic('eg: erc20.transfer(wallet, Enc(20000))')); - const amount20k = instance.encrypt64(20000); - const amount10k = instance.encrypt64(10000); - - const txT1 = await erc20['transfer(address,bytes)'](signers[2], amount20k); - const txT2 = await erc20['transfer(address,bytes)'](signers[3], amount10k); - await Promise.all([txT1.wait(), txT2.wait()]); - console.log('=> Carol received 20000 tokens'); - console.log('=> Dave received 10000 tokens'); - }); - -task('task:identity:transfer') - .addParam('erc20', 'ERC20 contract address') - .addParam('from', 'From wallet') - .addParam('to', 'To wallet') - .addParam('amount', 'Amount') - .setAction(async function (taskArguments: TaskArguments, { ethers }) { - const eSigners = await ethers.getSigners(); - const signers = getSigners(eSigners); - const erc20Address = taskArguments.erc20; - const from = taskArguments.from as keyof typeof signers; - const to = taskArguments.to as keyof typeof signers; - const amount = taskArguments.amount; - - const erc20 = (await ethers.getContractAt('CompliantERC20', erc20Address)) as any; - - const instance = await createInstance(erc20Address, signers[from], ethers); - - console.log(chalk.bold(`Sending ${amount} from ${from} to ${to}`)); - console.log(chalk.italic(`eg: erc20.transfer(to, Enc(${amount}))`)); - const encryptedAmount = instance.encrypt64(+amount); - const transaction = await erc20.connect(signers[from])['transfer(address,bytes)'](signers[to], encryptedAmount); - await transaction.wait(); - console.log(`=> ${amount} tokens have been transferred from ${from} to ${to}`); - }); - -task('task:identity:balanceOf') - .addParam('erc20', 'ERC20 contract address') - .addParam('user', 'User wallet') - .setAction(async function (taskArguments: TaskArguments, { ethers }) { - const eSigners = await ethers.getSigners(); - const signers = getSigners(eSigners); - const erc20Address = taskArguments.erc20; - const user = taskArguments.user as keyof typeof signers; - - const erc20 = (await ethers.getContractAt('CompliantERC20', erc20Address)) as any; - - const instance = await createInstance(erc20Address, signers[user], ethers); - - const token = instance.getPublicKey(erc20Address)!; - - const balance = await erc20.connect(signers[user]).balanceOf(signers[user], token.publicKey, token.signature); - console.log(`=> ${chalk.bold('Balance')}: ${instance.decrypt(erc20Address, balance)} tokens`); - }); diff --git a/tasks/taskTFHE.ts b/tasks/taskTFHE.ts index 8d672f06..f82dc80a 100644 --- a/tasks/taskTFHE.ts +++ b/tasks/taskTFHE.ts @@ -3,171 +3,181 @@ import { task } from 'hardhat/config'; import type { TaskArguments } from 'hardhat/types'; import path from 'path'; -task('task:computeACLAddress').setAction(async function (taskArguments: TaskArguments, { ethers }) { - const deployer = (await ethers.getSigners())[9].address; - const aclAddress = ethers.getCreateAddress({ - from: deployer, - nonce: 1, // using nonce of 1 for the ACL contract (0 for original implementation, +1 for proxy) - }); - const envFilePath = path.join(__dirname, '../lib/.env.acl'); - const content = `ACL_CONTRACT_ADDRESS=${aclAddress}\n`; - try { - fs.writeFileSync(envFilePath, content, { flag: 'w' }); - console.log(`ACL address ${aclAddress} written successfully!`); - } catch (err) { - console.error('Failed to write ACL address:', err); - } - - const solidityTemplate = `// SPDX-License-Identifier: BSD-3-Clause-Clear +task('task:computeACLAddress') + .addParam('privateKey', 'The deployer private key') + .setAction(async function (taskArguments: TaskArguments, { ethers }) { + const deployer = new ethers.Wallet(taskArguments.privateKey).address; + const aclAddress = ethers.getCreateAddress({ + from: deployer, + nonce: 1, // using nonce of 1 for the ACL contract (0 for original implementation, +1 for proxy) + }); + const envFilePath = path.join(__dirname, '../lib/.env.acl'); + const content = `ACL_CONTRACT_ADDRESS=${aclAddress}\n`; + try { + fs.writeFileSync(envFilePath, content, { flag: 'w' }); + console.log(`ACL address ${aclAddress} written successfully!`); + } catch (err) { + console.error('Failed to write ACL address:', err); + } + + const solidityTemplate = `// SPDX-License-Identifier: BSD-3-Clause-Clear pragma solidity ^0.8.24; address constant aclAdd = ${aclAddress};\n`; - try { - fs.writeFileSync('./lib/ACLAddress.sol', solidityTemplate, { encoding: 'utf8', flag: 'w' }); - console.log('./lib/ACLAddress.sol file generated successfully!'); - } catch (error) { - console.error('Failed to write ./lib/ACLAddress.sol', error); - } -}); - -task('task:computeTFHEExecutorAddress').setAction(async function (taskArguments: TaskArguments, { ethers }) { - const deployer = (await ethers.getSigners())[9].address; - const execAddress = ethers.getCreateAddress({ - from: deployer, - nonce: 3, // using nonce of 3 for the TFHEExecutor contract (2 for original implementation, +1 for proxy) + try { + fs.writeFileSync('./lib/ACLAddress.sol', solidityTemplate, { encoding: 'utf8', flag: 'w' }); + console.log('./lib/ACLAddress.sol file generated successfully!'); + } catch (error) { + console.error('Failed to write ./lib/ACLAddress.sol', error); + } }); - const envFilePath = path.join(__dirname, '../lib/.env.exec'); - const content = `TFHE_EXECUTOR_CONTRACT_ADDRESS=${execAddress}\n`; - try { - fs.writeFileSync(envFilePath, content, { flag: 'w' }); - console.log(`TFHEExecutor address ${execAddress} written successfully!`); - } catch (err) { - console.error('Failed to write TFHEExecutor address:', err); - } - const solidityTemplateCoprocessor = `// SPDX-License-Identifier: BSD-3-Clause-Clear +task('task:computeTFHEExecutorAddress') + .addParam('privateKey', 'The deployer private key') + .setAction(async function (taskArguments: TaskArguments, { ethers }) { + const deployer = new ethers.Wallet(taskArguments.privateKey).address; + const execAddress = ethers.getCreateAddress({ + from: deployer, + nonce: 3, // using nonce of 3 for the TFHEExecutor contract (2 for original implementation, +1 for proxy) + }); + const envFilePath = path.join(__dirname, '../lib/.env.exec'); + const content = `TFHE_EXECUTOR_CONTRACT_ADDRESS=${execAddress}\n`; + try { + fs.writeFileSync(envFilePath, content, { flag: 'w' }); + console.log(`TFHEExecutor address ${execAddress} written successfully!`); + } catch (err) { + console.error('Failed to write TFHEExecutor address:', err); + } + + const solidityTemplateCoprocessor = `// SPDX-License-Identifier: BSD-3-Clause-Clear pragma solidity ^0.8.24; address constant tfheExecutorAdd = ${execAddress};\n`; - try { - fs.writeFileSync('./lib/TFHEExecutorAddress.sol', solidityTemplateCoprocessor, { encoding: 'utf8', flag: 'w' }); - console.log('./lib/TFHEExecutorAddress.sol file generated successfully!'); - } catch (error) { - console.error('Failed to write ./lib/TFHEExecutorAddress.sol', error); - } -}); - -task('task:computeKMSVerifierAddress').setAction(async function (taskArguments: TaskArguments, { ethers }) { - const deployer = (await ethers.getSigners())[9].address; - const kmsVerfierAddress = ethers.getCreateAddress({ - from: deployer, - nonce: 5, // using nonce of 5 for the KMSVerifier contract (4 for original implementation, +1 for proxy) + try { + fs.writeFileSync('./lib/TFHEExecutorAddress.sol', solidityTemplateCoprocessor, { encoding: 'utf8', flag: 'w' }); + console.log('./lib/TFHEExecutorAddress.sol file generated successfully!'); + } catch (error) { + console.error('Failed to write ./lib/TFHEExecutorAddress.sol', error); + } }); - const envFilePath = path.join(__dirname, '../lib/.env.kmsverifier'); - const content = `KMS_VERIFIER_CONTRACT_ADDRESS=${kmsVerfierAddress}\n`; - try { - fs.writeFileSync(envFilePath, content, { flag: 'w' }); - console.log(`KMSVerifier address ${kmsVerfierAddress} written successfully!`); - } catch (err) { - console.error('Failed to write KMSVerifier address:', err); - } - const solidityTemplate = `// SPDX-License-Identifier: BSD-3-Clause-Clear +task('task:computeKMSVerifierAddress') + .addParam('privateKey', 'The deployer private key') + .setAction(async function (taskArguments: TaskArguments, { ethers }) { + const deployer = new ethers.Wallet(taskArguments.privateKey).address; + const kmsVerfierAddress = ethers.getCreateAddress({ + from: deployer, + nonce: 5, // using nonce of 5 for the KMSVerifier contract (4 for original implementation, +1 for proxy) + }); + const envFilePath = path.join(__dirname, '../lib/.env.kmsverifier'); + const content = `KMS_VERIFIER_CONTRACT_ADDRESS=${kmsVerfierAddress}\n`; + try { + fs.writeFileSync(envFilePath, content, { flag: 'w' }); + console.log(`KMSVerifier address ${kmsVerfierAddress} written successfully!`); + } catch (err) { + console.error('Failed to write KMSVerifier address:', err); + } + + const solidityTemplate = `// SPDX-License-Identifier: BSD-3-Clause-Clear pragma solidity ^0.8.24; address constant kmsVerifierAdd = ${kmsVerfierAddress};\n`; - try { - fs.writeFileSync('./lib/KMSVerifierAddress.sol', solidityTemplate, { encoding: 'utf8', flag: 'w' }); - console.log('./lib/KMSVerifierAddress.sol file generated successfully!'); - } catch (error) { - console.error('Failed to write ./lib/KMSVerifierAddress.sol', error); - } -}); - -task('task:computeInputVerifierAddress').setAction(async function (taskArguments: TaskArguments, { ethers }) { - // this script also compute the coprocessor address from its private key - const deployer = (await ethers.getSigners())[9].address; - const inputVerfierAddress = ethers.getCreateAddress({ - from: deployer, - nonce: 7, // using nonce of 7 for the InputVerifier contract (6 for original implementation, +1 for proxy) + try { + fs.writeFileSync('./lib/KMSVerifierAddress.sol', solidityTemplate, { encoding: 'utf8', flag: 'w' }); + console.log('./lib/KMSVerifierAddress.sol file generated successfully!'); + } catch (error) { + console.error('Failed to write ./lib/KMSVerifierAddress.sol', error); + } }); - const envFilePath = path.join(__dirname, '../lib/.env.inputverifier'); - const content = `INPUT_VERIFIER_CONTRACT_ADDRESS=${inputVerfierAddress}\n`; - try { - fs.writeFileSync(envFilePath, content, { flag: 'w' }); - console.log(`InputVerifier address ${inputVerfierAddress} written successfully!`); - } catch (err) { - console.error('Failed to write InputVerifier address:', err); - } - const solidityTemplate = `// SPDX-License-Identifier: BSD-3-Clause-Clear +task('task:computeInputVerifierAddress') + .addParam('privateKey', 'The deployer private key') + .setAction(async function (taskArguments: TaskArguments, { ethers }) { + // this script also compute the coprocessor address from its private key + const deployer = new ethers.Wallet(taskArguments.privateKey).address; + const inputVerfierAddress = ethers.getCreateAddress({ + from: deployer, + nonce: 7, // using nonce of 7 for the InputVerifier contract (6 for original implementation, +1 for proxy) + }); + const envFilePath = path.join(__dirname, '../lib/.env.inputverifier'); + const content = `INPUT_VERIFIER_CONTRACT_ADDRESS=${inputVerfierAddress}\n`; + try { + fs.writeFileSync(envFilePath, content, { flag: 'w' }); + console.log(`InputVerifier address ${inputVerfierAddress} written successfully!`); + } catch (err) { + console.error('Failed to write InputVerifier address:', err); + } + + const solidityTemplate = `// SPDX-License-Identifier: BSD-3-Clause-Clear pragma solidity ^0.8.24; address constant inputVerifierAdd = ${inputVerfierAddress};\n`; - try { - fs.writeFileSync('./lib/InputVerifierAddress.sol', solidityTemplate, { encoding: 'utf8', flag: 'w' }); - console.log('./lib/InputVerifierAddress.sol file generated successfully!'); - } catch (error) { - console.error('Failed to write ./lib/InputVerifierAddress.sol', error); - } - - const coprocAddress = new ethers.Wallet(process.env.PRIVATE_KEY_COPROCESSOR_ACCOUNT!).address; - const envFilePath2 = path.join(__dirname, '../lib/.env.coprocessor'); - const content2 = `COPROCESSOR_ADDRESS=${coprocAddress}\n`; - try { - fs.writeFileSync(envFilePath2, content2, { flag: 'w' }); - console.log(`Coprocessor address ${coprocAddress} written successfully!`); - } catch (err) { - console.error('Failed to write InputVerifier address:', err); - } - - const solidityTemplate2 = `// SPDX-License-Identifier: BSD-3-Clause-Clear + try { + fs.writeFileSync('./lib/InputVerifierAddress.sol', solidityTemplate, { encoding: 'utf8', flag: 'w' }); + console.log('./lib/InputVerifierAddress.sol file generated successfully!'); + } catch (error) { + console.error('Failed to write ./lib/InputVerifierAddress.sol', error); + } + + const coprocAddress = new ethers.Wallet(process.env.PRIVATE_KEY_COPROCESSOR_ACCOUNT!).address; + const envFilePath2 = path.join(__dirname, '../lib/.env.coprocessor'); + const content2 = `COPROCESSOR_ADDRESS=${coprocAddress}\n`; + try { + fs.writeFileSync(envFilePath2, content2, { flag: 'w' }); + console.log(`Coprocessor address ${coprocAddress} written successfully!`); + } catch (err) { + console.error('Failed to write InputVerifier address:', err); + } + + const solidityTemplate2 = `// SPDX-License-Identifier: BSD-3-Clause-Clear pragma solidity ^0.8.24; address constant coprocessorAdd = ${coprocAddress};\n`; - try { - fs.writeFileSync('./lib/CoprocessorAddress.sol', solidityTemplate2, { encoding: 'utf8', flag: 'w' }); - console.log('./lib/CoprocessorAddress.sol file generated successfully!'); - } catch (error) { - console.error('Failed to write ./lib/CoprocessorAddress.sol', error); - } -}); - -task('task:computeFHEPaymentAddress').setAction(async function (taskArguments: TaskArguments, { ethers }) { - const deployer = (await ethers.getSigners())[9].address; - const fhePaymentAddress = ethers.getCreateAddress({ - from: deployer, - nonce: 9, // using nonce of 9 for the FHEPayment contract (8 for original implementation, +1 for proxy) + try { + fs.writeFileSync('./lib/CoprocessorAddress.sol', solidityTemplate2, { encoding: 'utf8', flag: 'w' }); + console.log('./lib/CoprocessorAddress.sol file generated successfully!'); + } catch (error) { + console.error('Failed to write ./lib/CoprocessorAddress.sol', error); + } }); - const envFilePath = path.join(__dirname, '../lib/.env.fhepayment'); - const content = `FHE_PAYMENT_CONTRACT_ADDRESS=${fhePaymentAddress}\n`; - try { - fs.writeFileSync(envFilePath, content, { flag: 'w' }); - console.log(`FHEPayment address ${fhePaymentAddress} written successfully!`); - } catch (err) { - console.error('Failed to write FHEPayment address:', err); - } - const solidityTemplate = `// SPDX-License-Identifier: BSD-3-Clause-Clear +task('task:computeFHEPaymentAddress') + .addParam('privateKey', 'The deployer private key') + .setAction(async function (taskArguments: TaskArguments, { ethers }) { + const deployer = new ethers.Wallet(taskArguments.privateKey).address; + const fhePaymentAddress = ethers.getCreateAddress({ + from: deployer, + nonce: 9, // using nonce of 9 for the FHEPayment contract (8 for original implementation, +1 for proxy) + }); + const envFilePath = path.join(__dirname, '../lib/.env.fhepayment'); + const content = `FHE_PAYMENT_CONTRACT_ADDRESS=${fhePaymentAddress}\n`; + try { + fs.writeFileSync(envFilePath, content, { flag: 'w' }); + console.log(`FHEPayment address ${fhePaymentAddress} written successfully!`); + } catch (err) { + console.error('Failed to write FHEPayment address:', err); + } + + const solidityTemplate = `// SPDX-License-Identifier: BSD-3-Clause-Clear pragma solidity ^0.8.24; address constant fhePaymentAdd = ${fhePaymentAddress};\n`; - try { - fs.writeFileSync('./lib/FHEPaymentAddress.sol', solidityTemplate, { encoding: 'utf8', flag: 'w' }); - console.log('./lib/FHEPaymentAddress.sol file generated successfully!'); - } catch (error) { - console.error('Failed to write ./lib/FHEPaymentAddress.sol', error); - } -}); + try { + fs.writeFileSync('./lib/FHEPaymentAddress.sol', solidityTemplate, { encoding: 'utf8', flag: 'w' }); + console.log('./lib/FHEPaymentAddress.sol file generated successfully!'); + } catch (error) { + console.error('Failed to write ./lib/FHEPaymentAddress.sol', error); + } + }); diff --git a/tasks/utils.ts b/tasks/utils.ts deleted file mode 100644 index 1a8bacf4..00000000 --- a/tasks/utils.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { Signer } from 'ethers'; -import fhevmjs, { FhevmInstance, getPublicKeyCallParams } from 'fhevmjs'; -import { ethers as hethers } from 'hardhat'; - -let publicKey: string | undefined; -let chainId: number; - -export const createInstance = async (contractAddress: string, account: Signer, ethers: typeof hethers) => { - // 1. Get chain id - const provider = ethers.provider; - - const network = await provider.getNetwork(); - chainId = +network.chainId.toString(); // Need to be a number - try { - // Get blockchain public key - const ret = await provider.call(getPublicKeyCallParams()); - const decoded = ethers.AbiCoder.defaultAbiCoder().decode(['bytes'], ret); - publicKey = decoded[0]; - } catch (e) { - publicKey = undefined; - } - - const instance = await fhevmjs.createInstance({ chainId, publicKey }); - - await generatePublicKey(contractAddress, account, instance); - - return instance; -}; - -const generatePublicKey = 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); -}; diff --git a/test/kmsVerifier/kmsVerifier.ts b/test/kmsVerifier/kmsVerifier.ts index 38edf33c..b4bba0be 100644 --- a/test/kmsVerifier/kmsVerifier.ts +++ b/test/kmsVerifier/kmsVerifier.ts @@ -22,7 +22,7 @@ describe('KMSVerifier', function () { // to avoid messing up other tests if used on the real node, in parallel testing const origKMSAdd = dotenv.parse(fs.readFileSync('lib/.env.kmsverifier')).KMS_VERIFIER_CONTRACT_ADDRESS; - const deployer = (await ethers.getSigners())[9]; + const deployer = new ethers.Wallet(process.env.PRIVATE_KEY_FHEVM_DEPLOYER!).connect(ethers.provider); const kmsVerifier = await this.kmsFactory.attach(origKMSAdd); expect(await kmsVerifier.getVersion()).to.equal('KMSVerifier v0.1.0'); diff --git a/test/upgrades/upgrades.ts b/test/upgrades/upgrades.ts index 48fdd23c..59034f47 100644 --- a/test/upgrades/upgrades.ts +++ b/test/upgrades/upgrades.ts @@ -92,7 +92,7 @@ describe('Upgrades', function () { it('original owner upgrades the original ACL and transfer ownership', async function () { const origACLAdd = dotenv.parse(fs.readFileSync('lib/.env.acl')).ACL_CONTRACT_ADDRESS; - const deployer = (await ethers.getSigners())[9]; + const deployer = new ethers.Wallet(process.env.PRIVATE_KEY_FHEVM_DEPLOYER!).connect(ethers.provider); const acl = await this.aclFactory.attach(origACLAdd, deployer); expect(await acl.getVersion()).to.equal('ACL v0.1.0'); const newaclFactoryUpgraded = await ethers.getContractFactory('ACLUpgradedExample', deployer);