Skip to content

Commit

Permalink
Merge pull request #13 from bobanetwork/wsdt/fix-local-rpc
Browse files Browse the repository at this point in the history
fix: local rpc
  • Loading branch information
wsdt authored Aug 13, 2024
2 parents ae88bd8 + 7ca8045 commit 681faef
Show file tree
Hide file tree
Showing 6 changed files with 122 additions and 129 deletions.
143 changes: 67 additions & 76 deletions contracts/script/deploy-local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,29 @@ import * as fs from "fs";
import * as path from "path";
import * as dotenv from "dotenv";
import { ethers } from "ethers";
import {DEFAULT_SNAP_VERSION, getLocalIpAddress, isPortInUse} from "./utils";
import {DEFAULT_SNAP_VERSION, deleteIgnitionDeployments, getLocalIpAddress, isPortInUse} from "./utils";
import {execPromise} from './utils'
import {SimpleAccountFactory__factory, TokenPaymaster__factory, VerifyingPaymaster__factory} from "../typechain-types";

dotenv.config();

const deployAddr = ethers.getAddress(
"0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266"
);
const deployKey =
"0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
const deployAddr = ethers.getAddress("0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266");
const deployKey = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
const bundlerAddr = ethers.getAddress("0xB834a876b7234eb5A45C0D5e693566e8842400bB");
const builderPrivkey = "0xf91be07ef5a01328015cae4f2e5aefe3c4577a90abb8e2e913fe071b0e3732ed";
const clientOwner = ethers.getAddress("0x77Fe14A710E33De68855b0eA93Ed8128025328a9");
const clientPrivkey = "0x541b3e3b20b8bb0e5bae310b2d4db4c8b7912ba09750e6ff161b7e67a26a9bf7";
const ha0Owner = ethers.getAddress("0x2A9099A58E0830A4Ab418c2a19710022466F1ce7");
const ha0Privkey = "0x75cd983f0f4714969b152baa258d849473732905e2301467303dacf5a09fdd57";
const ha1Owner = ethers.getAddress("0xE073fC0ff8122389F6e693DD94CcDc5AF637448e");
const ha1Privkey = "0x7c0c629efc797f8c5f658919b7efbae01275470d59d03fdeb0fca1e6bd11d7fa";

const bundlerAddr = ethers.getAddress(
"0xB834a876b7234eb5A45C0D5e693566e8842400bB"
);
const builderPrivkey =
"0xf91be07ef5a01328015cae4f2e5aefe3c4577a90abb8e2e913fe071b0e3732ed";

const ha0Owner = ethers.getAddress(
"0x2A9099A58E0830A4Ab418c2a19710022466F1ce7"
);
const ha0Privkey =
"0x75cd983f0f4714969b152baa258d849473732905e2301467303dacf5a09fdd57";

const ha1Owner = ethers.getAddress(
"0xE073fC0ff8122389F6e693DD94CcDc5AF637448e"
);
/** @DEV Configurations */
const snapEnv = '../snap-account-abstraction-keyring/packages/snap/.env-local'
const l2Provider = new ethers.JsonRpcProvider('http://localhost:9545');
const l2Wallet = new ethers.Wallet(deployKey, l2Provider);
let aaConfigFile = fs.readFileSync('../snap-account-abstraction-keyring/packages/snap/src/constants/aa-config.ts', 'utf8');


const updateEnvVariable = (key: string, value: string, envPath: string) => {
Expand Down Expand Up @@ -60,25 +56,30 @@ const parseLocalDeployAddresses = () => {
address: transaction.contractAddress ?? "",
}));

// const hybridAccount = jsonData.transactions
// .map((transaction: any) => {
// if (
// transaction.contractName === "HybridAccountFactory" &&
// transaction.function === "createAccount(address,uint256)"
// ) {
// return {
// contractName: "HybridAccount",
// address: transaction.additionalContracts[0].address,
// };
// }
// })
// .filter((ha: any) => ha); // filter out undefined values

// contracts.push(...hybridAccount);

console.log("Parsed JSON data:", contracts);
return contracts;
} catch (err) {
console.error("Error reading or parsing the file:", err);
}
};

const deleteIgnitionDeployments = () => {
const deploymentsPath = path.resolve(__dirname, "../ignition/deployments");
if (fs.existsSync(deploymentsPath)) {
fs.rmSync(deploymentsPath, { recursive: true, force: true });
console.log("Ignition deployments folder deleted.");
} else {
console.log(
"Ignition deployments folder does not exist. Skipping deletion."
);
}
};

// TODO: fix .env file loading. Currently .env needs to be in /script directory
async function main() {
try {
if (!isPortInUse(8545) && !isPortInUse(9545)) {
Expand Down Expand Up @@ -119,25 +120,25 @@ async function main() {
BACKEND_URL: process.env.BACKEND_URL,
};

console.log('vars are: ', baseDeployVars)
try {
await execPromise(
"forge script --json --broadcast --rpc-url http://127.0.0.1:9545 deploy.s.sol",
undefined,
path.resolve(__dirname, "../script/"),
baseDeployVars
);
}catch (e) {
console.log('error is: ', e);
}
await execPromise(
"forge script --json --broadcast --rpc-url http://localhost:9545 deploy.s.sol:DeployExample -vvvvv",
undefined,
path.resolve(__dirname, "./"),
baseDeployVars
);

const contracts = parseLocalDeployAddresses();
const hcHelperAddr = contracts?.find((c) => c.contractName === "HCHelper")?.address;
const hybridAccountAddr = contracts?.find((c) => c.contractName === "HybridAccount")?.address;

if (!hcHelperAddr || !hybridAccountAddr) {
throw Error("HC Helper not defined!");
}

const entrypoint = contracts?.find((c) => c.contractName === "EntryPoint")?.address
const envVars = {
HC_HELPER_ADDR: contracts?.find((c) => c.contractName === "HCHelper")
?.address,
HC_SYS_ACCOUNT: contracts?.find((c) => c.contractName === "HybridAccount")
?.address,
HC_HELPER_ADDR: contracts?.find((c) => c.contractName === "HCHelper")?.address,
HC_SYS_ACCOUNT: contracts?.find((c) => c.contractName === "HybridAccount")?.address,
HC_SYS_OWNER: ha0Owner,
HC_SYS_PRIVKEY: ha0Privkey,
ENTRY_POINTS: entrypoint,
Expand All @@ -154,11 +155,7 @@ async function main() {
);

deleteIgnitionDeployments();
console.log(
"HA ADDRESS: ",
contracts?.find((c) => c.contractName === "HybridAccount")?.address
);
console.log("path: ", path.resolve(__dirname, "../"));

const ignitionOutput = await execPromise(
"npx hardhat ignition deploy ./ignition/modules/TokenPrice.ts --network boba_local",
["y"],
Expand All @@ -181,6 +178,13 @@ async function main() {
}
const tokenPriceAddress = tokenPriceMatch[1];
console.log("TokenPrice Contract deployed to: ", tokenPriceAddress);
console.log('using hybridAcc: ', hybridAccountAddr);

/** @DEV Permit Caller */
const abi = ["function PermitCaller(address caller, bool allow) external"];
const hybridAccount = new ethers.Contract(hybridAccountAddr, abi, l2Wallet);
const tx = await hybridAccount.PermitCaller(tokenPriceAddress, true);
await tx.wait();

// Frontend env vars
const frontendEnvPath = path.resolve(__dirname, "../../frontend/.env-local");
Expand Down Expand Up @@ -228,7 +232,7 @@ async function main() {
updateEnvVariable("OC_PRIVKEY", deployKey, backendEnvPath);
updateEnvVariable(
"HC_HELPER_ADDR",
contracts?.find((c) => c.contractName === "HCHelper")?.address ?? "",
hcHelperAddr,
backendEnvPath
);

Expand All @@ -239,7 +243,7 @@ async function main() {
const contractsEnvPath = path.resolve(__dirname, "../.env");
updateEnvVariable(
"HYBRID_ACCOUNT",
contracts?.find((c) => c.contractName === "HybridAccount")?.address ?? "",
hybridAccountAddr,
contractsEnvPath
);
updateEnvVariable(
Expand All @@ -254,7 +258,7 @@ async function main() {
);
updateEnvVariable(
"HC_HELPER_ADDR",
contracts?.find((c) => c.contractName === "HCHelper")?.address ?? "",
hcHelperAddr,
contractsEnvPath
);
updateEnvVariable("PRIVATE_KEY", deployKey, contractsEnvPath);
Expand All @@ -264,46 +268,33 @@ async function main() {
contractsEnvPath
);

const snapSiteEnvFolder = '../snap-account-abstraction-keyring/packages/site/'
updateEnvVariable('USE_LOCAL_NETWORK', "true", `${snapSiteEnvFolder}/.env`)
updateEnvVariable('USE_LOCAL_NETWORK', "true", `${snapSiteEnvFolder}/.env.development`)
updateEnvVariable('USE_LOCAL_NETWORK', "true", `${snapSiteEnvFolder}/.env.development.hc`)

/** @DEV Snap */
const snapEnv = '../snap-account-abstraction-keyring/packages/snap/.env-local'
const l2provider = new ethers.JsonRpcProvider('http://localhost:9545');

/** @DEV deploy simple account factory */
const wallet = new ethers.Wallet(deployKey, l2provider);
const SimpleAccountFactory = new SimpleAccountFactory__factory(wallet);
const SimpleAccountFactory = new SimpleAccountFactory__factory(l2Wallet);
const simpleAccountFactoryContract = await SimpleAccountFactory.deploy(entrypoint!);
await simpleAccountFactoryContract.waitForDeployment();
console.log('SimpleAccountFactory: ', simpleAccountFactoryContract.target)

/** @DEV deploy verifying paymaster */
const VerifyingPaymasterFactory = new VerifyingPaymaster__factory(wallet);
const verifyingPaymasterContract = await VerifyingPaymasterFactory.deploy(entrypoint, wallet.address);
const VerifyingPaymasterFactory = new VerifyingPaymaster__factory(l2Wallet);
const verifyingPaymasterContract = await VerifyingPaymasterFactory.deploy(entrypoint, l2Wallet.address);
await verifyingPaymasterContract.waitForDeployment();
console.log('Verifying paymaster: ', verifyingPaymasterContract.target)

/** @DEV deploy the token paymaster */
const TokenPaymasterFactory = new TokenPaymaster__factory(wallet);
const TokenPaymasterFactory = new TokenPaymaster__factory(l2Wallet);
const tokenPaymasterContract = await TokenPaymasterFactory.deploy(
simpleAccountFactoryContract.target, entrypoint, wallet.address);
simpleAccountFactoryContract.target, entrypoint, l2Wallet.address);
await tokenPaymasterContract.waitForDeployment();
console.log('Verifying paymaster: ', tokenPaymasterContract.target)


let content = fs.readFileSync('../snap-account-abstraction-keyring/packages/snap/src/constants/aa-config.ts', 'utf8');
console.log('Verifying tokenPaymaster: ', tokenPaymasterContract.target)

const localConfigRegex = /(\[CHAIN_IDS\.LOCAL\]:\s*{[\s\S]*?entryPoint:\s*')([^']*)(\'[\s\S]*?simpleAccountFactory:\s*')([^']*)(\'[\s\S]*?bobaPaymaster:\s*')([^']*)(\'[\s\S]*?})/;

content = content.replace(localConfigRegex, (match, before1, oldEntryPoint, middle1, oldSimpleAccountFactory, middle2, oldBobaPaymaster, after) => {
aaConfigFile = aaConfigFile.replace(localConfigRegex, (match, before1, oldEntryPoint, middle1, oldSimpleAccountFactory, middle2, oldBobaPaymaster, after) => {
return `${before1}${ENTRYPOINT}${middle1}${simpleAccountFactoryContract.target}${middle2}${tokenPaymasterContract.target}${after}`;
});

// Update the AA-config
fs.writeFileSync('../snap-account-abstraction-keyring/packages/snap/src/constants/aa-config.ts', content, 'utf8');
fs.writeFileSync('../snap-account-abstraction-keyring/packages/snap/src/constants/aa-config.ts', aaConfigFile, 'utf8');

// Update LOCAL_ENTRYPOINT
updateEnvVariable(
Expand Down
15 changes: 6 additions & 9 deletions contracts/script/deploy.s.sol
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ contract DeployExample is Script {
EntryPoint public entrypoint;
HCHelper public hcHelper;
HybridAccount public hybridAccount;
TokenPrice public tokenPrice;
SimpleAccount public simpleAccount;
SimpleAccountFactory public saf;

Expand Down Expand Up @@ -52,7 +51,6 @@ contract DeployExample is Script {
IEntryPoint(entrypoint),
address(hcHelper)
);
tokenPrice = new TokenPrice(payable(hybridAccount));
saf = new SimpleAccountFactory(entrypoint);
simpleAccount = new SimpleAccount(IEntryPoint(entrypoint));
}
Expand All @@ -62,19 +60,19 @@ contract DeployExample is Script {
hcHelper.initialize(deployerAddress, address(hybridAccount));
hcHelper.SetPrice(0);
}
(bool suc, ) = address(entrypoint).call{value: 1 ether}("");
require(suc, "Failed to send 1 ETH to entrypoint");
uint256 minBalance = 0.01 ether;
(uint112 bal, , , , ) = entrypoint.deposits(address(hybridAccount));
if (bal < 0.01 ether) {
entrypoint.depositTo{value: 0.01 ether - bal}(
address(address(hybridAccount))
);
if (bal < minBalance) {
uint256 amountToDeposit = minBalance - bal;
entrypoint.depositTo{value: amountToDeposit}(deployerAddress);
}

// register url, add credit
hcHelper.RegisterUrl(address(hybridAccount), backendURL);
hcHelper.AddCredit(address(hybridAccount), 100);
// permit caller
hybridAccount.initialize(deployerAddress);
hybridAccount.PermitCaller(address(tokenPrice), true);
// fund the bundler
(bool success, ) = bundlerAddress.call{value: 1 ether}("");
require(success, "ETH transfer failed");
Expand All @@ -84,7 +82,6 @@ contract DeployExample is Script {
console.log("ENTRY_POINTS=", address(entrypoint));
console.log("HC_HELPER_ADDR=", address(hcHelper));
console.log("OC_HYBRID_ACCOUNT=", address(hybridAccount));
console.log("TEST_TOKEN_PRICE=", address(tokenPrice));
console.log("SIMPLE_ACCOUNT=", address(simpleAccount));
console.log("CLIENT_PRIVKEY=", deployerPrivateKey);
console.log("HC_SYS_OWNER", address(deployerAddress));
Expand Down
30 changes: 22 additions & 8 deletions contracts/script/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export const isPortInUse = (port: number) => {
export const execPromise = (
command: string,
inputs: string[] = [],
cwd: ProcessEnvOptions["cwd"] = undefined,
cwd: any = undefined,
env?: NodeJS.ProcessEnv
): Promise<string> => {
return new Promise((resolve, reject) => {
Expand All @@ -67,13 +67,15 @@ export const execPromise = (
let stderr = "";

child.stdout.on("data", (data) => {
stdout += data.toString();
console.log(data.toString());
const output = data.toString();
stdout += output;
console.log(output);
});

child.stderr.on("data", (data) => {
stderr += data.toString();
console.error(data.toString());
const output = data.toString();
stderr += output;
console.error(output);
});

const stdinStream = new Readable({
Expand All @@ -87,13 +89,25 @@ export const execPromise = (

stdinStream.pipe(child.stdin);

child.on("close", (code) => {
child.on("close", (code, e) => {
if (code !== 0) {
console.log(stdout)
reject(new Error(`${command} Command failed with exit code ${code}`));
console.error(`${command} Command failed with exit code ${code} ${e}`);
reject(new Error(`${command} Command failed with exit code ${code} ${e}`));
} else {
resolve(stdout);
}
});
});
};

export const deleteIgnitionDeployments = () => {
const deploymentsPath = path.resolve(__dirname, "../ignition/deployments");
if (fs.existsSync(deploymentsPath)) {
fs.rmSync(deploymentsPath, { recursive: true, force: true });
console.log("Ignition deployments folder deleted.");
} else {
console.log(
"Ignition deployments folder does not exist. Skipping deletion."
);
}
};
22 changes: 11 additions & 11 deletions frontend/src/components/AccountAlert.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,17 @@ const NetworkAlert = () => {
)
}

if (Number(state.chain) !== 28882) {
return (
<div className="flex w-6/12 rounded-md shadow-sm border m-auto my-2 p-5 items-center justify-start gap-2 bg-yellow-600 margin-auto">
<AlertTriangle color="#fff" />
<p className="text-sm text-white">
Wrong Network! Please connect to boba sepolia network.
</p>
<Button onClick={switchToBobaSepolia} variant="secondary">Switch To Boba Sepolia</Button>
</div>
)
}
// if (Number(state.chain) !== 28882) {
// return (
// <div className="flex w-6/12 rounded-md shadow-sm border m-auto my-2 p-5 items-center justify-start gap-2 bg-yellow-600 margin-auto">
// <AlertTriangle color="#fff" />
// <p className="text-sm text-white">
// Wrong Network! Please connect to boba sepolia network.
// </p>
// <Button onClick={switchToBobaSepolia} variant="secondary">Switch To Boba Sepolia</Button>
// </div>
// )
// }

return <></>

Expand Down
Loading

0 comments on commit 681faef

Please sign in to comment.