Skip to content

Commit

Permalink
Add example for hardhat loader (#568)
Browse files Browse the repository at this point in the history
Part of #563.

Add tests and example for hardhat drectory loader.
  • Loading branch information
Tamika Nomara committed Jul 9, 2021
1 parent 8cbd9cd commit 401fb5f
Show file tree
Hide file tree
Showing 16 changed files with 3,166 additions and 21 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/pull-request.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,9 @@ jobs:
cargo run --package examples --example deployments
cargo run --package examples --example events
cargo run --package examples --example revert
cargo run --package examples-generate
cargo run --package examples --example linked
if [ "$PK" ] && [ "$INFURA_PROJECT_ID" ]; then
cargo run --package examples-generate
cargo run --package examples --example rinkeby
cargo run --package examples --example sources
fi
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,7 @@ Cargo.lock

node_modules/
examples/*/build/
examples/*/artifacts
examples/*/cache

.idea
48 changes: 48 additions & 0 deletions ethcontract-common/src/artifact/hardhat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,7 @@ struct HardHatContract {
#[cfg(test)]
mod test {
use super::*;
use std::path::PathBuf;
use web3::ethabi::ethereum_types::BigEndianHash;
use web3::types::{H256, U256};

Expand Down Expand Up @@ -827,4 +828,51 @@ mod test {
assert_eq!(a.networks.len(), 1);
assert_eq!(a.networks["4"].address, address(0xBA));
}

fn hardhat_dir() -> PathBuf {
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push("../examples/hardhat/deployments");
path
}

#[test]
fn load_from_directory() {
let artifact = HardHatLoader::new()
.load_from_directory(hardhat_dir())
.unwrap();

assert_eq!(artifact.len(), 1);

let a = artifact.get("DeployedContract").unwrap();
assert_eq!(a.name, "DeployedContract");
assert_eq!(a.networks.len(), 2);
assert_eq!(
a.networks["4"].address,
"0x4E29B76eC7d20c58A6B156CB464594a4ae39FdEd"
.parse()
.unwrap()
);
assert_eq!(
a.networks["4"].deployment_information,
Some(DeploymentInformation::TransactionHash(
"0x0122d15a8d394b8f9e45c15b7d3e5365bbf7122a15952246676e2fe7eb858f35"
.parse()
.unwrap()
))
);
assert_eq!(
a.networks["1337"].address,
"0x29BE0588389993e7064C21f00761303eb51373F5"
.parse()
.unwrap()
);
assert_eq!(
a.networks["1337"].deployment_information,
Some(DeploymentInformation::TransactionHash(
"0xe0631d7f749fe73f94e59f6e25ff9b925980e8e29ed67b8f862ec76a783ea06e"
.parse()
.unwrap()
))
);
}
}
22 changes: 13 additions & 9 deletions examples/generate/build.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
use ethcontract_generate::loaders::TruffleLoader;
use ethcontract_generate::loaders::HardHatLoader;
use ethcontract_generate::ContractBuilder;

fn main() {
let out_dir = std::env::var("OUT_DIR").unwrap();
let dest = std::path::Path::new(&out_dir).join("rust_coin.rs");
let dest = std::path::Path::new(&out_dir).join("contracts.rs");

let contract = TruffleLoader::new()
.load_contract_from_file("../truffle/build/contracts/RustCoin.json")
.unwrap();
ContractBuilder::new()
.generate(&contract)
.unwrap()
.write_to_file(dest)
let artifact = HardHatLoader::new()
.deny_by_name("localhost")
.load_from_directory("../hardhat/deployments")
.unwrap();

for contract in artifact.iter() {
ContractBuilder::new()
.generate(contract)
.unwrap()
.write_to_file(&dest)
.unwrap();
}
}
52 changes: 41 additions & 11 deletions examples/generate/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,52 @@
use ethcontract::prelude::*;
use std::env;

include!(concat!(env!("OUT_DIR"), "/rust_coin.rs"));
include!(concat!(env!("OUT_DIR"), "/contracts.rs"));

const RINKEBY_CHAIN_ID: u64 = 4;

#[tokio::main]
async fn main() {
let http = Http::new("http://localhost:9545").expect("create transport failed");
let account = {
let pk = env::var("PK").expect("PK is not set");
let key: PrivateKey = pk.parse().expect("invalid PK");
Account::Offline(key, Some(RINKEBY_CHAIN_ID))
};
let infura_url = {
let project_id = env::var("INFURA_PROJECT_ID").expect("INFURA_PROJECT_ID is not set");
format!("https://rinkeby.infura.io/v3/{}", project_id)
};

let http = Http::new(&infura_url).expect("create transport failed");
let web3 = Web3::new(http);

let instance = RustCoin::builder(&web3)
.gas(4_712_388.into())
.deploy()
.await
.expect("deployment failed");
let instance = {
let mut instance = DeployedContract::deployed(&web3)
.await
.expect("locating deployed contract failed");
instance.defaults_mut().from = Some(account);
instance
};

println!(
"using {} ({}) at {:?}",
instance.name().call().await.expect("get name failed"),
instance.symbol().call().await.expect("get name failed"),
instance.address()
"Using contract at {:?} deployed with transaction {:?}",
instance.address(),
instance.deployment_information(),
);

println!(
" value before: {}",
instance.value().call().await.expect("get value failed")
);
println!(" incrementing (this may take a while)...");
instance
.increment()
.confirmations(1) // wait for 1 block confirmation
.send()
.await
.expect("increment failed");
println!(
" value after: {}",
instance.value().call().await.expect("get value failed")
);
}
23 changes: 23 additions & 0 deletions examples/hardhat/contracts/DeployedContract.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
pragma solidity ^0.8.0;

/**
* @dev Rinkeby deployed contract used in examples.
*/
contract DeployedContract {
mapping(address => uint256) private values;

/**
* @dev Gets the current value set in the contract for the `msg.sender`.
*/
function value() public view returns (uint256) {
return values[msg.sender];
}

/**
* @dev Increments the value for the `msg.sender` by 1.
*/
function increment() public returns (uint256) {
values[msg.sender]++;
return (values[msg.sender]);
}
}
4 changes: 4 additions & 0 deletions examples/hardhat/deploy/00_init.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = async ({getNamedAccounts, deployments}) => {
const {deployer} = await getNamedAccounts();
await deployments.deploy('DeployedContract', {from: deployer});
};
1 change: 1 addition & 0 deletions examples/hardhat/deployments/localhost/.chainId
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
1337
101 changes: 101 additions & 0 deletions examples/hardhat/deployments/localhost/DeployedContract.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
{
"address": "0x29BE0588389993e7064C21f00761303eb51373F5",
"abi": [
{
"inputs": [],
"name": "increment",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "value",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
}
],
"transactionHash": "0xe0631d7f749fe73f94e59f6e25ff9b925980e8e29ed67b8f862ec76a783ea06e",
"receipt": {
"to": null,
"from": "0x58F7bf16796d069a7590525eBD507921036Ce82B",
"contractAddress": "0x29BE0588389993e7064C21f00761303eb51373F5",
"transactionIndex": 0,
"gasUsed": "175807",
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"blockHash": "0xbbc976772d85d908aedad3c88de6dd0f7adb6dc7af7524f6cf6bd3c726521c7e",
"transactionHash": "0xe0631d7f749fe73f94e59f6e25ff9b925980e8e29ed67b8f862ec76a783ea06e",
"logs": [],
"blockNumber": 151,
"cumulativeGasUsed": "175807",
"status": 1,
"byzantium": true
},
"args": [],
"solcInputHash": "d7ef70c507cb995ea3e81152c437ca74",
"metadata": "{\"compiler\":{\"version\":\"0.8.0+commit.c7dfd78e\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[],\"name\":\"increment\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"value\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}],\"devdoc\":{\"details\":\"Rinkeby deployed contract used in examples.\",\"kind\":\"dev\",\"methods\":{\"increment()\":{\"details\":\"Increments the value for the `msg.sender` by 1.\"},\"value()\":{\"details\":\"Gets the current value set in the contract for the `msg.sender`.\"}},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/DeployedContract.sol\":\"DeployedContract\"},\"evmVersion\":\"istanbul\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":false,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/DeployedContract.sol\":{\"content\":\"pragma solidity ^0.8.0;\\n\\n/**\\n * @dev Rinkeby deployed contract used in examples.\\n */\\ncontract DeployedContract {\\n mapping(address => uint256) private values;\\n\\n /**\\n * @dev Gets the current value set in the contract for the `msg.sender`.\\n */\\n function value() public view returns (uint256) {\\n return values[msg.sender];\\n }\\n\\n /**\\n * @dev Increments the value for the `msg.sender` by 1.\\n */\\n function increment() public returns (uint256) {\\n values[msg.sender]++;\\n return (values[msg.sender]);\\n }\\n}\\n\",\"keccak256\":\"0x85ebb83768b7c9a3ca7db76560b0833e0e57d29716df381ef14e72a144e4e64d\"}},\"version\":1}",
"bytecode": "0x608060405234801561001057600080fd5b50610239806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c80633fa4f2451461003b578063d09de08a14610059575b600080fd5b610043610077565b6040516100509190610166565b60405180910390f35b6100616100bd565b60405161006e9190610166565b60405180910390f35b60008060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905090565b60008060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600081548092919061010e9061018b565b91905055506000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905090565b61016081610181565b82525050565b600060208201905061017b6000830184610157565b92915050565b6000819050919050565b600061019682610181565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8214156101c9576101c86101d4565b5b600182019050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fdfea2646970667358221220993b4e7128d49168b275476d44461ca250c375b19974365fa3372ff084874faf64736f6c63430008000033",
"deployedBytecode": "0x608060405234801561001057600080fd5b50600436106100365760003560e01c80633fa4f2451461003b578063d09de08a14610059575b600080fd5b610043610077565b6040516100509190610166565b60405180910390f35b6100616100bd565b60405161006e9190610166565b60405180910390f35b60008060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905090565b60008060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600081548092919061010e9061018b565b91905055506000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905090565b61016081610181565b82525050565b600060208201905061017b6000830184610157565b92915050565b6000819050919050565b600061019682610181565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8214156101c9576101c86101d4565b5b600182019050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fdfea2646970667358221220993b4e7128d49168b275476d44461ca250c375b19974365fa3372ff084874faf64736f6c63430008000033",
"devdoc": {
"details": "Rinkeby deployed contract used in examples.",
"kind": "dev",
"methods": {
"increment()": {
"details": "Increments the value for the `msg.sender` by 1."
},
"value()": {
"details": "Gets the current value set in the contract for the `msg.sender`."
}
},
"version": 1
},
"userdoc": {
"kind": "user",
"methods": {},
"version": 1
},
"storageLayout": {
"storage": [
{
"astId": 6,
"contract": "contracts/DeployedContract.sol:DeployedContract",
"label": "values",
"offset": 0,
"slot": "0",
"type": "t_mapping(t_address,t_uint256)"
}
],
"types": {
"t_address": {
"encoding": "inplace",
"label": "address",
"numberOfBytes": "20"
},
"t_mapping(t_address,t_uint256)": {
"encoding": "mapping",
"key": "t_address",
"label": "mapping(address => uint256)",
"numberOfBytes": "32",
"value": "t_uint256"
},
"t_uint256": {
"encoding": "inplace",
"label": "uint256",
"numberOfBytes": "32"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"language": "Solidity",
"sources": {
"contracts/DeployedContract.sol": {
"content": "pragma solidity ^0.8.0;\n\n/**\n * @dev Rinkeby deployed contract used in examples.\n */\ncontract DeployedContract {\n mapping(address => uint256) private values;\n\n /**\n * @dev Gets the current value set in the contract for the `msg.sender`.\n */\n function value() public view returns (uint256) {\n return values[msg.sender];\n }\n\n /**\n * @dev Increments the value for the `msg.sender` by 1.\n */\n function increment() public returns (uint256) {\n values[msg.sender]++;\n return (values[msg.sender]);\n }\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": false,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"abi",
"evm.bytecode",
"evm.deployedBytecode",
"evm.methodIdentifiers",
"metadata",
"devdoc",
"userdoc",
"storageLayout",
"evm.gasEstimates"
],
"": [
"ast"
]
}
},
"metadata": {
"useLiteralContent": true
}
}
}
1 change: 1 addition & 0 deletions examples/hardhat/deployments/rinkeby/.chainId
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
4
Loading

0 comments on commit 401fb5f

Please sign in to comment.