Skip to content

Commit

Permalink
Merge branch 'dev' into feat/dry-run-impersonator
Browse files Browse the repository at this point in the history
  • Loading branch information
saeta-eth committed Oct 24, 2024
2 parents 9367891 + d03f057 commit 0883af6
Show file tree
Hide file tree
Showing 29 changed files with 2,531 additions and 453 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/check-branch-name.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ jobs:
switch(base) {
case 'main':
case 'alpha': {
if (!/^hotfix\/[A-Za-z0-9-_\.]+$/.test(branch)) {
console.error(`::error::Branch name must start with 'hotfix/*' for PRs to ${base}`)
if (!/^(hotfix|release)\/[A-Za-z0-9-_\.]+$/.test(branch)) {
console.error(`::error::Branch name must start with 'hotfix/*' or 'release/*' for PRs to ${base}`)
process.exit(1)
}
break;
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/commitlint-pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ jobs:
validateSingleCommit: false
types: |
hotfix
release
feat
fix
chore
Expand Down
15 changes: 0 additions & 15 deletions SECURITY.md

This file was deleted.

2 changes: 1 addition & 1 deletion lerna.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
"npmClient": "pnpm",
"packages": ["packages/*"],
"exact": true,
"version": "2.18.2"
"version": "2.18.4"
}
4 changes: 0 additions & 4 deletions netlify.toml

This file was deleted.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"lint:fix:js": "prettier --write '{packages,examples}/**/*.{js,ts}' && eslint --fix '{packages,examples}/**/*.{js,ts}'",
"lint:fix:sol": "prettier --write '{packages,examples}/*/{contracts,src}/**/*.sol'",
"lint:fix": "pnpm run '/^lint:fix:(js|sol)/'",
"build": "pnpm -r --if-present run clean && pnpm -r --filter @usecannon/builder --filter @usecannon/cli --filter hardhat-cannon --filter @usecannon/api run build",
"build": "pnpm -r --if-present --filter @usecannon/builder --filter @usecannon/cli --filter hardhat-cannon --filter @usecannon/api run clean && pnpm -r --filter @usecannon/builder --filter @usecannon/cli --filter hardhat-cannon --filter @usecannon/api run build",
"watch": "pnpm -r --parallel --filter @usecannon/builder --filter @usecannon/cli run watch",
"version-alpha": "lerna version prerelease --no-private",
"version-patch": "lerna version patch --no-private",
Expand Down
5 changes: 3 additions & 2 deletions packages/builder/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@usecannon/builder",
"version": "2.18.2",
"version": "2.18.4",
"description": "Assembles cannonfile.toml manifests into cannon packages.",
"main": "dist/src/index.js",
"types": "dist/src/index.d.ts",
Expand Down Expand Up @@ -43,7 +43,8 @@
"typedoc-plugin-zod": "^1.2.0"
},
"dependencies": {
"@synthetixio/router": "^3.4.0",
"@usecannon/router": "^4.0.1",
"@usecannon/web-solc": "0.5.1",
"axios": "^1.7.2",
"axios-retry": "^4.4.2",
"buffer": "^6.0.3",
Expand Down
40 changes: 20 additions & 20 deletions packages/builder/src/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -877,32 +877,32 @@ export const chainDefinitionSchema = z
privateSourceCode: z
.boolean()
.describe(
'Turns off inclusion of source code in packages. When set to true, Cannon cannot verify contracts on Etherscan.'
'Turns off inclusion of source code in packages. When set to true, Cannon cannot verify contracts on Etherscan. Defaults to false.'
)
.optional(),
/**
* Description for the package
*/
description: z.string().describe('Description for the package').optional(),
/**
* Keywords for search indexing
*/
keywords: z.array(z.string()).describe('Keywords for search indexing').optional(),
/**
* Any deployers that could publish this package. Will be used for automatic version management.
*/
deployers: z
.array(
z.string().refine((val) => !!val.match(RegExp(/^0x[a-fA-F0-9]{40}$/, 'gm')), {
message: 'Invalid Ethereum address',
})
)
.describe('Any deployers that could publish this package. Will be used for automatic version management.')
.optional(),
})
.merge(
z
.object({
/**
* Description for the package
*/
description: z.string().describe('Description for the package'),
/**
* Keywords for search indexing
*/
keywords: z.array(z.string()).describe('Keywords for search indexing'),
/**
* Any deployers that could publish this package. Will be used for automatic version management.
*/
deployers: z
.array(
z.string().refine((val) => !!val.match(RegExp(/^0x[a-fA-F0-9]{40}$/, 'gm')), {
message: 'Invalid Ethereum address',
})
)
.optional()
.describe('Any deployers that could publish this package. Will be used for automatic version management.'),
/**
* Object that allows the definition of values for use in next operations
* ```toml
Expand Down
16 changes: 7 additions & 9 deletions packages/builder/src/steps/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import Debug from 'debug';
import _ from 'lodash';
import * as viem from 'viem';
import { z } from 'zod';
import { generateRouter } from '@usecannon/router';
import { computeTemplateAccesses, mergeTemplateAccesses } from '../access-recorder';
import { ChainBuilderRuntime } from '../runtime';
import { routerSchema } from '../schemas';
Expand All @@ -13,6 +14,7 @@ import {
getMergedAbiFromContractPaths,
} from '../util';
import { template } from '../utils/template';
import { compileContract } from '../utils/compile';

const debug = Debug('cannon:builder:router');

Expand Down Expand Up @@ -101,8 +103,6 @@ const routerStep = {
config: Config,
packageState: PackageState
): Promise<ChainArtifacts> {
const { generateRouter, getCompileInput, compileContract } = await import('@synthetixio/router');

debug('exec', config);

const contracts = config.contracts.map((n) => {
Expand All @@ -111,16 +111,18 @@ const routerStep = {
throw new Error(`contract not found: ${n}`);
}

const contractName = n.replace('.', '_'); // Use step name, and replace '.' in case is pointing to an import.

return {
constructorArgs: contract.constructorArgs,
abi: contract.abi,
deployedAddress: contract.address ? viem.getAddress(contract.address) : contract.address, // Make sure address is checksum encoded
deployTxnHash: contract.deployTxnHash,
deployTxnBlockNumber: '',
deployTimestamp: '',
contractName: contract.contractName,
contractName: contractName,
sourceName: contract.sourceName,
contractFullyQualifiedName: `${contract.sourceName}:${contract.contractName}`,
contractFullyQualifiedName: `${contract.sourceName}:${contractName}`,
};
});

Expand All @@ -134,11 +136,7 @@ const routerStep = {

debug('router source code', sourceCode);

// On Mainnet, use default local solc evmVersion, for everything else, 'paris'
const evmVersion = [1, 5, 11155111].includes(runtime.chainId) ? undefined : 'paris';

const inputData = getCompileInput(contractName, sourceCode, evmVersion);
const solidityInfo = await compileContract(contractName, sourceCode, evmVersion);
const { input: inputData, output: solidityInfo } = await compileContract(contractName, sourceCode);

// the ABI is entirely based on the fallback call so we have to generate ABI here
const routableAbi = getMergedAbiFromContractPaths(ctx, config.contracts);
Expand Down
81 changes: 81 additions & 0 deletions packages/builder/src/utils/compile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import * as viem from 'viem';
import { fetchSolc } from '@usecannon/web-solc';

interface CompileResult {
sourceName: string;
contractName: string;
abi: viem.Abi;
metadata: string;
solcVersion: string;
assembly: string;
bytecode: string;
deployedBytecode: string;
gasEstimates: {
creation: {
codeDepositCost: string;
executionCost: string;
totalCost: string;
};
external: {
'': string;
};
};
}

export async function compileContract(
contractName: string,
sourceCode: string,
evmVersion = 'paris',
compilerVersion = '0.8.27'
) {
const { compile, stopWorker } = await fetchSolc(compilerVersion);

const sourceName = `${contractName}.sol`;

const input = {
language: 'Solidity',
sources: {
[sourceName]: {
content: sourceCode,
},
},
settings: {
outputSelection: {
'*': { '*': ['*'] },
},
evmVersion,
},
};

try {
const output = await compile(input);

if (output.errors) {
throw new Error(
[
`There was an error when compiling "${contractName}".`,
...output.errors.map((err: { message: string }) => err.message),
].join(' ')
);
}

const info = (output.contracts as any)[sourceName][contractName];
const metadata = JSON.parse(info.metadata);

const result = {
contractName,
sourceName,
abi: info.abi,
metadata: info.metadata,
solcVersion: metadata.compiler.version,
assembly: info.evm.assembly,
bytecode: info.evm.bytecode.object,
deployedBytecode: info.evm.deployedBytecode.object,
gasEstimates: info.evm.gasEstimates,
} satisfies CompileResult;

return { input, output: result };
} finally {
stopWorker();
}
}
2 changes: 1 addition & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@usecannon/cli",
"version": "2.18.2",
"version": "2.18.4",
"description": "Utility for instantly loading cannon packages in standalone contexts",
"main": "dist/src/index.js",
"scripts": {
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/src/commands/build.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,9 @@ describe('build', () => {
let provider: viem.PublicClient & viem.WalletClient & viem.TestClient;

beforeEach(() => {
jest
.spyOn(helpers, 'loadCannonfile')
.mockResolvedValue({ def: { danglingDependencies: {}, getDeployers: () => [] } } as any);
jest.spyOn(helpers, 'loadCannonfile').mockResolvedValue({
def: { danglingDependencies: {}, getDeployers: () => [], isPublicSourceCode: () => false },
} as any);
provider = makeFakeProvider();
jest.spyOn(buildCommand, 'build').mockResolvedValue({ outputs: {}, provider, runtime: {} as any });
jest.spyOn(utilProvider, 'resolveProvider').mockResolvedValue({ provider: provider as any, signers: [] });
Expand Down
10 changes: 6 additions & 4 deletions packages/cli/src/commands/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ interface Params {
wipe?: boolean;
dryRun?: boolean;
plugins?: boolean;
publicSourceCode?: boolean;
privateSourceCode?: boolean;
rpcUrl?: string;
registryPriority?: 'local' | 'onchain' | 'offline';
gasPrice?: bigint;
Expand All @@ -72,7 +72,7 @@ export async function build({
wipe = false,
dryRun,
plugins = true,
publicSourceCode = false,
privateSourceCode = false,
rpcUrl,
registryPriority,
gasPrice,
Expand Down Expand Up @@ -123,7 +123,9 @@ export async function build({
getDefaultSigner,
snapshots: chainId === CANNON_CHAIN_ID,
allowPartialDeploy: chainId !== CANNON_CHAIN_ID,
publicSourceCode,
// ChainBuilderRuntime uses publicSourceCode to determine if source code should be included in the package
publicSourceCode: !privateSourceCode,

gasPrice,
gasFee,
priorityGasFee,
Expand Down Expand Up @@ -198,7 +200,7 @@ export async function build({
log('Version: ' + cyanBright(`${pkgVersion}`));
log('Preset: ' + cyanBright(`${preset}`) + (preset == 'main' ? gray(' (default)') : ''));
log('Chain ID: ' + cyanBright(`${chainId}`));
if (publicSourceCode) {
if (!privateSourceCode) {
log(`Private Source Code: ${cyanBright('false')} ${gray('(source code will be included in the package)')}`);
} else {
log(`Private Source Code: ${cyanBright('true')} ${gray('(source code will not be included in the resulting package)')}`);
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/util/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,7 @@ async function prepareBuildConfig(
getSigner,
getDefaultSigner,
upgradeFrom: options.upgradeFrom,
privateSourceCode: !def.isPublicSourceCode(),
wipe: options.wipe,
dryRun: options.dryRun,
overrideResolver,
Expand Down
6 changes: 6 additions & 0 deletions packages/cli/src/write-script/render-ethers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { EOL } from 'node:os';
import { Transform } from 'node:stream';

/**
* This script is used to deploy contracts using Ethers.js.
* It outputs a JS script that can be used to deploy contracts and execute transactions.
* Note: Make sure you add `.js` extension to the output file.
*/

import type { DumpLine, DumpRenderer } from './types';
const header = `/* eslint-disable */
Expand Down
Loading

0 comments on commit 0883af6

Please sign in to comment.