Commit 1d581f43 authored by Quentin Bramas's avatar Quentin Bramas
Browse files

clean AFTER the tutorial

parent f07f20ce
import fs from 'fs';
import web3 from '../common/web3';
import contractAbi from '../contract/contract_paperBlock2_sol_paperBlock.abi';
import contractAbi from '../contract/firstContract_sol_TestValue.abi.json';
const contract = new web3.eth.Contract(contractAbi, {
gasPrice: web3.utils.toWei('50', 'gwei')
});
const buildContract = require('./buildContract');
console.log('building contract')
export async function deployContract()
{
const compiledSource = fs.readFileSync('contract/firstContract_sol_TestValue.bin', 'utf8');
export default async () => {
let contract = null;
try{
const compiledSource = fs.readFileSync('contract/contract_paperBlock2_sol_paperBlock.bin', 'utf8')
const contractAbi = JSON.parse(fs.readFileSync('contract/contract_paperBlock2_sol_paperBlock.abi', 'utf8'))
// Smart contract EVM bytecode as hex
contract.options.data = '0x' + compiledSource;
contract = new web3.eth.Contract(contractAbi, {
gasPrice: web3.utils.toWei('50', 'gwei')
});
// Smart contract EVM bytecode as hex
contract.options.data = '0x' + compiledSource;
} catch(e) {
console.error('error while building contract', e);
}
console.log('deploying contract');
const result = await contract
.deploy({
return contract.deploy({
arguments: []
})
.send({
gas: 1500000
})
console.log('contract deployed');
console.log(result);
gas: 1500000,
from: web3.eth.defaultAccount
}, (a,b) => console.log('send callback', a,b))
.on('error', (a,b) => console.log('error', a,b))
.on('transactionHash', (a,b) => console.log('transactionHash', a,b))
.on('receipt', (a,b) => console.log('receipt', a,b))
.on('confirmation', (a,b) => console.log('confirmation', a,b));
}
......@@ -7,6 +7,8 @@ export default function(accountFile) {
{
return web3.eth.accounts.privateKeyToAccount(fs.readFileSync(accountFile, 'utf8'));
}
console.log(accountFile, 'account file does not exist');
process.exit(1);
let account = web3.eth.accounts.create();
fs.writeFileSync(accountFile, account.privateKey, 'utf8');
return account;
}
import fs from 'fs';
import web3 from '../common/web3';
let account = web3.eth.accounts.privateKeyToAccount(
fs.readFileSync('.accountSSS', 'utf8')
);
web3.eth.defaultAccount = account.address;
web3.eth.accounts.wallet.add(account);
console.log('current account', account.address);
const abi = JSON.parse(fs.readFileSync('contract/firstContract_sol_TestValue.abi', 'utf8'));
async function deployContract()
{
const compiledSource = fs.readFileSync('contract/firstContract_sol_TestValue.bin', 'utf8');
const contract = new web3.eth.Contract(abi, {
gasPrice: web3.utils.toWei('50', 'gwei'),
from: web3.eth.defaultAccount
});
// Smart contract EVM bytecode as hex
contract.options.data = '0x' + compiledSource;
console.log('deploying contract');
const result = await contract
.deploy({
arguments: []
})
.send({
gas: 1500000
})
console.log('contract deployed');
console.log(result);
}
async function interact() {
const contract = new web3.eth.Contract(abi, {
gasPrice: web3.utils.toWei('50', 'gwei'),
from: web3.eth.defaultAccount
});
contract.options.address = '0xBcD41F2B2E895D6521C414276b8103936b778bd6'
console.log('sending transaction');
/*
const result = await contract.methods.donate().send({
value: web3.utils.toWei('1', 'ether'),
gas: 100000
});*/
/*const result = await contract.methods.changeWinnerString("I love SSS").send({
gas: 100000
});*/
/*const result = await contract.methods.bestDonator().call();*/
const gasEstimate = await contract.methods.withdraw().estimateGas();
const result = await contract.methods.withdraw().send({
gas: gasEstimate
});
console.log(result)
}
//deployContract();
interact();
import fs from 'fs';
import web3 from '../common/web3';
import * as commands from '../common/commands';
if(process.argv.length < 4)
{
console.log('Usage:\nnode cli.js PRIVATE_KEY_FILE COMMAND ARGS');
process.exit(1);
}
let account = web3.eth.accounts.privateKeyToAccount(
fs.readFileSync(process.argv[2], 'utf8')
);
web3.eth.defaultAccount = account.address;
web3.eth.accounts.wallet.add(account);
console.log('current account', account.address);
commands.setFrom(account.address);
const command = process.argv[3];
if(!commands[command])
{
console.log('Available commands:');
Object.keys(commands).forEach(c => console.log(' -',c));
process.exit(1);
}
console.log('running command', command);
try{
commands[command].apply(null, process.argv.slice(4)).then(console.log);
}
catch (e)
{
console.error('error while running command', command, e);
}
import web3 from '../common/web3';
import createOrLoadAccount from './createOrLoadAccount';
import * as commands from '../common/commands';
import createContractCommand from './createContractCommand';
commands['createContract'] = createContractCommand;
if(process.argv.length < 4)
{
console.log('Usage:\nnode index.js PRIVATE_KEY_FILE COMMAND ARGS');
process.exit(1);
}
let account = createOrLoadAccount(process.argv[2]);
web3.eth.defaultAccount = account.address;
web3.eth.accounts.wallet.add(account);
console.log('account: '+account.address)
const command = process.argv[3];
if(!commands[command])
{
console.log('Available commands:');
Object.keys(commands).forEach(c => console.log(' -',c));
process.exit(1);
}
console.log('running command', command);
try{
commands[command].apply(null, process.argv.slice(4)).then(console.log);
}
catch (e)
{
console.error('error while running command', command, e);
}
......@@ -6,7 +6,6 @@ import web3 from "../common/web3"
import account from "./account"
import * as commands from '../common/commands';
import { prettyPrefix } from './prettyAddr';
import prettyAddr from './prettyAddr'
const setPrivateKey = (key) => (state) => {
web3.eth.defaultAccount = account(key).address;
......@@ -42,7 +41,7 @@ const setPrivateKeyForm = (state) => {
return setPrivateKey(value)(state)
}
export default ({state}) => {
export default () => {
let allKeys = localStorage.getItem("allPrivateKeys");
if(!allKeys){
allKeys = []
......@@ -51,39 +50,22 @@ export default ({state}) => {
{
allKeys = JSON.parse(allKeys);
}
return !state.privateKey
? <div class="container">
<form onSubmit={preventDefault(setPrivateKeyForm)}>
<div class="form-group">
<label for="privateKeyInput">Private Key</label>
<input type="text" class="form-control" id="privateKeyInput" aria-describedby="emailHelp" placeholder="0x..." />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<div class="form-group">
<div>Or choose an existing one :</div><ul>
{allKeys.map((k, i) => <li key={i}>
<a href="#"
onclick={preventDefault(setPrivateKey(k.privateKey))}
>
{k.prefix || k.address}
</a>
</li>
)}
</ul>
</div>
</form>
</div>
: <div>
<h2>Your account: {prettyAddr(account(state).address)}
<small>
<a href="#" onclick={preventDefault((state) => ({...state, privateKey:null}))}>
change
return <form onSubmit={preventDefault(setPrivateKeyForm)}>
<div class="form-group">
<label for="privateKeyInput">Private Key</label>
<input type="text" class="form-control" id="privateKeyInput" aria-describedby="emailHelp" placeholder="0x..." />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<div class="form-group">
<div>Or choose an existing one :</div><ul>
{allKeys.map((k, i) => <li key={i}>
<a href="#"
onclick={preventDefault(setPrivateKey(k.privateKey))}
>
{k.prefix || k.address}
</a>
</small>
</h2>
<small>
full address: {account(state).address}
</small>
</div>
</li>
)}
</ul></div>
</form>
}
import {h} from 'hyperapp';
import { donate, getDonation, bestDonator} from '../common/commands'
import { preventDefault, targetValue } from "@hyperapp/events"
import {dispatchAsync} from './dispatchAsync';
import account from './account';
const actionFetchDonation = (state) => async (dispatch) => {
dispatch({
...state,
donated: 'loading'
})
const d = await getDonation();
const best = await bestDonator();
dispatch({
...state,
bestDonator: best,
donated: d
})
}
const actionDonate = (state) => async (dispatch) => {
dispatch({
...state,
donated: 'loading'
})
const d = await donate(state.donationInput);
actionFetchDonation(state)(dispatch);
}
export default ({state}) => !state.privateKey ?
'you need to be connected to donate'
: <div>
amount donated: {state.donated}<br/>
<button
onclick={preventDefault(dispatchAsync(actionFetchDonation))}
class="btn btn-primary">
Fetch donation
</button><br/>
{
state.bestDonator
&& (
state.bestDonator.toLowerCase() === account(state).address.toLowerCase()
? 'you are the best donator'
: 'you are not the best donator'
)
}<br/>
<input
type="number"
value={state.donationInput}
oninput={(state, event) => ({...state, donationInput:event.target.value})}
/>
<button
onclick={preventDefault(dispatchAsync(actionDonate))}
class="btn btn-primary">
Donate
</button>
</div>
import {h} from 'hyperapp';
import { winnerString } from '../common/commands'
import { preventDefault, targetValue } from "@hyperapp/events"
import {dispatchAsync} from './dispatchAsync';
export const fetchWinnerString = (state) => async (dispatch) => {
dispatch({
...state,
winnerString: 'loading'
})
const ws = await winnerString();
dispatch({
...state,
winnerString: ws
})
}
export default ({state}) => <div>
<h2>{state.winnerString}</h2>
<button
onclick={preventDefault(dispatchAsync(fetchWinnerString))}
class="btn btn-primary">
Fetch Winner String
</button>
</div>
import {h} from 'hyperapp';
import { donate, getDonation, bestDonator,changeWinnerString} from '../common/commands'
import { preventDefault, targetValue } from "@hyperapp/events"
import {dispatchAsync} from './dispatchAsync';
import account from './account';
import {fetchWinnerString} from './WinnerString';
const actionSetWinnerString = (state) => async (dispatch) => {
dispatch({
...state,
winnerString: 'loading'
})
const d = await changeWinnerString(state.winnerStringInput);
fetchWinnerString(state)(dispatch);
}
export default ({state}) => ((
state.privateKey &&
state.bestDonator &&
state.bestDonator.toLowerCase() === account(state).address.toLowerCase())
? <div>
<input
type="text"
value={state.winnerStringInput}
oninput={(state, event) => ({...state, winnerStringInput:event.target.value})}
/>
<button
onclick={preventDefault(dispatchAsync(actionSetWinnerString))}
class="btn btn-primary">
Set winner String
</button>
</div>
: ''
)
......@@ -7,7 +7,6 @@ export default (state) => {
{
state = {privateKey: state};
}
if(!state.privateKey) return null
if(!cacheAccount[state.privateKey]) {
cacheAccount[state.privateKey] = web3.eth.accounts.privateKeyToAccount(state.privateKey);
}
......
import { h, app } from "hyperapp";
import { preventDefault, targetValue } from "@hyperapp/events"
import account from './account'
import * as commands from '../common/commands';
import web3 from '../common/web3';
import PrivateKeyForm from './PrivateKeyForm';
import PrivateKeyForm from './PrivateKeyForm'
import Reader from './Reader'
import Editor from './Editor'
import Reviewer from './Reviewer'
import Author from './Author'
import { dispatchAsync } from "./dispatchAsync"
import {v, _} from './utils'
import account from './account'
import prettyAddr from './prettyAddr'
import { fetchJournalPaper } from './JournalPaper';
/*
commands.journal('0xD70536239C9617b4A645E6a5be966b508b3b9e22').then(console.log)
console.log('web3',web3.utils)
console.log('defaultAccount',web3 && web3.eth.defaultAccount);
window.addEventListener('load', async () => {
// Modern dapp browsers...
if (window.ethereum) {
window.web3 = new Web3(ethereum);
try {
// Request account access if needed
await ethereum.enable();
// Acccounts now exposed
} catch (error) {
// User denied account access...
}
}
// Legacy dapp browsers...
else if (window.web3) {
window.web3 = new Web3(web3.currentProvider);
// Acccounts always exposed
}
// Non-dapp browsers...
else {
console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
}
});
*/
const setActiveTab = (activeTab) => (state) => ({...state, activeTab});
const tabs = [
{title:'Reader', component: Reader},
{title:'Author', component: Author},
{title:'Reviewer', component: Reviewer},
{title:'Editor', component: Editor},
];
const Layout = (state) => {
return <div class="container">
<PrivateKeyForm state={state} />
<br/>
<br/>
Hello
{ !state.privateKey
? <div class="container"><PrivateKeyForm /></div>
: <div><h2>Your account: {prettyAddr(account(state).address)} <small><a href="#" onclick={preventDefault((state) => ({...state, privateKey:null}))}>change</a></small></h2>
<small>full address: {account(state).address}</small>
</div>
}
<div>The journal: {prettyAddr(state.journalAdr)}</div>
<div>
{state.fetchingJournal && 'Loading...'}
{state.numPapers === null ? '' : state.numPapers+' papers'}
{' '}
<button
class="btn btn-info"
onclick={preventDefault(dispatchAsync((state) => async (dispatch) => {
console.log('fetching Journal')
dispatch({...state, fetchingJournal:true});
const r = await commands.journal(state.journalAdr);
dispatch({...state, numPapers:r.numPapers, fetchingJournal:false});
console.log('fetched journal', r);
}))}>
Fetch journal information
</button>
</div><br/>
<ul class="nav nav-tabs">
{
tabs.map(t => <li class="nav-item">
<a class={'nav-link'+(state.activeTab === t.title?' active':'')}
href="#"
onclick={preventDefault(setActiveTab(t.title))}>
{t.title}
</a>
</li>)
}
</ul>
<div class="tab-content" id="myTabContent">
{
tabs
.filter(t => state.activeTab === t.title)
.map(t => <div
title={t.title}
class={'tab-pane show'+(state.activeTab === t.title?' active':'')}
role="tabpanel">
<t.component state={state} />
</div>)
}
</div>
</div>
}
let defaultKey = localStorage.getItem('defaultPrivateKey');
if(defaultKey)
{
web3.eth.defaultAccount = account(defaultKey).address;
commands.setFrom(account(defaultKey).address);
web3.eth.accounts.wallet.add(account(defaultKey));
}
let paperMatch = window.location.search.match(/(\?|\&)paper=([^&]*)$/)
let defaultPaper = {
paperForm:{}
};
if(paperMatch)
{
try{
const paperForm = JSON.parse(decodeURIComponent(paperMatch[2]));
const paperFormJson = JSON.stringify(paperForm);
const paperFormHash = web3.utils.sha3(paperFormJson);
defaultPaper = {
paperForm,
paperFormJson,
paperFormHash
}
}
catch (e) { }//ignore errors
}
let journalPaperMatch = window.location.search.match(/(\?|\&)journalPaper=([^&]*)/)
console.log(journalPaperMatch)
app({
init: {
privateKey: '',
winnerString: '',
bestDonator: ''
journalAdr: '0x5353531074558f4b7fcf0d52fc3b11be1f07b6c1',
privateKey: defaultKey,
numPapers: null,
activeTab: 'Reader',
...defaultPaper
},
view: Layout,
node: document.getElementById("app"),
subscriptions: journalPaperMatch && ((action, props) => [
(dispatch, props) => {
if(!journalPaperMatch) return (() => {});
const idx = journalPaperMatch[2]
journalPaperMatch = false