Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added ContractCreator solidity example contract (#530) #531

Merged
merged 3 commits into from
Nov 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion contracts/solidity/modular/Token.sol
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,5 @@ contract Token {
function allowance(address owner, address spender) external view returns (uint balance) {
return allowed[owner][spender];
}
}
}

74 changes: 74 additions & 0 deletions contracts/yul/contract-creator/ContractCreator.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.20;

/**
* @notice The unit tests for the `ContractCreator` contract will utilize a predefined bytecode of a contract that inherits the `ITargetContract` interface.
*/
interface ITargetContract {
function setCount(uint _number) external;
function getCount() external view returns (uint);
}

contract ContractCreator {
event NewContractCreated(address contractAddress);

/// create(v, p, n) is used to create a new contract
/// `v`: The value (in wei) to be transferred to the newly created contract.
/// `p`: The address of the location in memory where the code for the new contract is stored.
/// `n`: The size of the code in memory.
function createNewContract(bytes memory bytecode) external payable {
address newContractAddress;
assembly {
// get msgValue
let msgValue := callvalue()

// get the size of the `bytecode`
let size := mload(bytecode)

// get actual bytecode
// @notice: This is done as `add(bytecode, 0x20)` because the first 32 bytes of the `bytecode` are often used to store the length of the bytecode,
// and the actual bytecode starts from 33rd byte. So by adding `0x20`, it's pointing to the actualy bytecode's starting position within the `bytecode` array
let actualByteCode := add(bytecode, 0x20)

// Create new contract using create(v, p, n) opcode
newContractAddress := create(msgValue, actualByteCode, size)

// check if the contract creation was sucessful
if iszero(extcodesize(newContractAddress)) {
revert(0, 0)
}
}
emit NewContractCreated(newContractAddress);
}


/// create2(v, p, n, s) is used to create a new contract
/// `v`: The value (in wei) to be transferred to the newly created contract.
/// `p`: The address of the location in memory where the code for the new contract is stored.
/// `n`: The size of the code in memory.
/// `s`: The random 256-bit salt
function create2NewContract(bytes memory bytecode, uint256 salt) external payable {
address newContractAddress;
assembly {
// get msgValue
let msgValue := callvalue()

// get the size of the `bytecode`
let size := mload(bytecode)

// get actual bytecode
// @notice: This is done as `add(bytecode, 0x20)` because the first 32 bytes of the `bytecode` are often used to store the length of the bytecode,
// and the actual bytecode starts from 33rd byte. So by adding `0x20`, it's pointing to the actualy bytecode's starting position within the `bytecode` array
let actualByteCode := add(bytecode, 0x20)

// Create new contract using create2(v, p, n, s) opcode
newContractAddress := create2(msgValue, actualByteCode, size, salt)

// check if the contract creation was sucessful
if iszero(extcodesize(newContractAddress)) {
revert (0,0)
}
}
emit NewContractCreated(newContractAddress);
}
}
2 changes: 1 addition & 1 deletion test/solidity/address/AssemblyAddress.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ describe('@solidityevmequiv3 AssemblyAddress', () => {
)

// @notice Remove the '0x' prefix from the expected contract bytecode, then calculate the length in bytes
// @notice Since each hexadeimal character represents 4 bits, and each bute is represented by 2 hexadecimal characters.
// @notice Since each hexadeimal character represents 4 bits, and each byte is represented by 2 hexadecimal characters.
// Therefore, the length of bytecode in bytes is half of the length of the bytecode in hexadecimal characters.
const expectedContractCodeSize =
expectedContractBytecode.replace('0x', '').length / 2
Expand Down
134 changes: 134 additions & 0 deletions test/yul/contract-creator/ContractCreator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*-
*
* Hedera Smart Contracts
*
* Copyright (C) 2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

const { expect } = require('chai')
const { ethers } = require('hardhat')

describe('@solidityequiv5 Contract Creator Tests', async () => {
let contractCreator, signers
const EXPECTED_COUNT = 3
const TARGET_CONTRACT_BYTECODE =
'0x608060405234801561000f575f80fd5b506101438061001d5f395ff3fe608060405234801561000f575f80fd5b5060043610610034575f3560e01c8063a87d942c14610038578063d14e62b814610056575b5f80fd5b610040610072565b60405161004d919061009b565b60405180910390f35b610070600480360381019061006b91906100e2565b61007a565b005b5f8054905090565b805f8190555050565b5f819050919050565b61009581610083565b82525050565b5f6020820190506100ae5f83018461008c565b92915050565b5f80fd5b6100c181610083565b81146100cb575f80fd5b50565b5f813590506100dc816100b8565b92915050565b5f602082840312156100f7576100f66100b4565b5b5f610104848285016100ce565b9150509291505056fea2646970667358221220af7141ab23a3458b57b18949d542040e5d9b03df8e389b9ab7b04d1780386cc564736f6c63430008140033'

const TARGET_CONTRACT_INTERFACE = [
{
inputs: [],
name: 'getCount',
outputs: [
{
internalType: 'uint256',
name: '',
type: 'uint256',
},
],
stateMutability: 'view',
type: 'function',
},
{
inputs: [
{
internalType: 'uint256',
name: '_number',
type: 'uint256',
},
],
name: 'setCount',
outputs: [],
stateMutability: 'nonpayable',
type: 'function',
},
]

before(async () => {
signers = await ethers.getSigners()
const contractCreatorFactory = await ethers.getContractFactory(
'ContractCreator'
)
contractCreator = await contractCreatorFactory.deploy()
})

it('Should create a new contract using create(v, p, n)', async () => {
// prepare createNewContract transaction
const transaction = await contractCreator.createNewContract(
TARGET_CONTRACT_BYTECODE
)

// wait for the receipt
const receipt = await transaction.wait()

// extract newContractAddress from event logs
const [newContractAddress] = receipt.events.map(
(e) => e.event === 'NewContractCreated' && e
)[0].args

// assert newContractAddress is valid
expect(ethers.utils.isAddress(newContractAddress)).to.be.true

// connect to target contract at the new created contract address
const targetContract = new ethers.Contract(
newContractAddress,
TARGET_CONTRACT_INTERFACE,
signers[0]
)

// interact with the target contract
await targetContract.setCount(EXPECTED_COUNT)
const count = await targetContract.getCount()

// assertion
expect(count).to.eq(EXPECTED_COUNT)
})

it('Should create a new contract using create2(v, p, n, s)', async () => {
// random 256-bit salt
const SALT = 36

// prepare create2NewContract transaction
const transaction = await contractCreator.create2NewContract(
TARGET_CONTRACT_BYTECODE,
SALT
)

// wait for the receipt
const receipt = await transaction.wait()

// extract newContractAddress from event logs
const [newContractAddress] = receipt.events.map(
(e) => e.event === 'NewContractCreated' && e
)[0].args

// assert newContractAddress is valid
expect(ethers.utils.isAddress(newContractAddress)).to.be.true

// connect to target contract at the new created contract address
const targetContract = new ethers.Contract(
newContractAddress,
TARGET_CONTRACT_INTERFACE,
signers[0]
)

// interact with the target contract
await targetContract.setCount(EXPECTED_COUNT)
const count = await targetContract.getCount()

// assertion
expect(count).to.eq(EXPECTED_COUNT)
})
})
Loading