Skip to content

Instantly share code, notes, and snippets.

@riordant
Last active March 19, 2018 20:08
Show Gist options
  • Save riordant/7bdf55e7f270fd61e57e7cf70d1300a0 to your computer and use it in GitHub Desktop.
Save riordant/7bdf55e7f270fd61e57e7cf70d1300a0 to your computer and use it in GitHub Desktop.
// setup ethers.js, sends an instance of a struct to an external function, and returns it the instance values.
//load in node: .load ~/path/to/file/ethers_setup.js
//first run testrpc locally.
var privkey = "0x{privkey}" //insert privkey from testrpc here
//dependancies
var solc = require('solc') //include solc application
var fs = require('fs') //include node file manipulation module
var ethers = require('ethers');
var TestRpc = require("ethereumjs-testrpc");
main();
async function main(){
//get contract
var contract_path = '/path/to/file/struct_io.sol'
var contract = fs.readFileSync(contract_path, 'utf8'); //'contract' now contains contract code as a string
//compile contract
var compiled = solc.compile(contract, 1) //compiles contract with optimiser. output var is an array of contracts indexed by Property (JS thing).
compiled
//get contract name, abi and bytecode.
var contractName = Object.keys(compiled.contracts)[0] //returned array is indexed by property. assuming single index array, pull the contract name.
var abi = compiled.contracts[contractName].interface
var bytecode = '0x' + compiled.contracts[contractName].bytecode
//create new wallet, using private key of wallet we have control of.
var wallet = new ethers.Wallet(privkey);
//set port of blockchain.
var port = 8545;
//setup access to blockchain.
var testRpc = TestRpc.server({
port,
logger: console,
blocktime: 0.5,
network_id: 15,
unlocked_accounts: [ wallet.address ],
accounts: [{
balance: '8000000000000000000000000000000000000000000000000000000000000000',
secretKey: wallet.privateKey
}]
});
//link wallet to blockchain.
var provider = new ethers.providers.JsonRpcProvider(`http://localhost:${port}`, { chainId: 15 });
wallet.provider = provider;
//setup contract for deployment.
var deployTransaction = ethers.Contract.getDeployTransaction(bytecode, abi);
//deploy contract.
var transaction;
let result = wallet.sendTransaction(deployTransaction).then(function(sendResult) {
transaction = {
from: sendResult.from,
nonce: sendResult.nonce
};
});
//get address of deployed contract.
var contractAddress = ethers.utils.getContractAddress(transaction);
//get deployed contract.
var contract = new ethers.Contract(contractAddress, abi, wallet);
//push test value..
contract.addTestStruct([100, "testing",[10, "sub testing"]]).then(function(result){ console.log(result); });
//return test value.
contract.tests(0).then(function(result){ console.log(result); });
// :)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment