Extract kredits module

This commit is contained in:
2018-04-09 02:09:07 +02:00
parent cb1208acaa
commit 7e04cef964
15 changed files with 343 additions and 320 deletions
+6 -8
View File
@@ -8,13 +8,11 @@ export default Controller.extend({
init() {
this._super(...arguments);
this.get('kredits.kreditsContract')
.then((contract) => {
contract.onproposalvoted = this._handleProposalVoted.bind(this);
contract.onproposalcreated = this._handleProposalCreated.bind(this);
contract.onproposalexecuted = this._handleProposalExecuted.bind(this);
// TODO: transfer on the token contract
});
let contract = this.get('kredits.kredits').Operator.contract;
contract.onproposalvoted = this._handleProposalVoted.bind(this);
contract.onproposalcreated = this._handleProposalCreated.bind(this);
contract.onproposalexecuted = this._handleProposalExecuted.bind(this);
// TODO: transfer on the token contract
},
contributors: alias('model.contributors'),
@@ -50,7 +48,7 @@ export default Controller.extend({
return;
}
proposal = this.get('kredits').getProposalById(proposalId);
proposal = this.get('kredits.kredits').Operator.getById(proposalId);
this.get('proposals').pushObject(proposal);
},
+37
View File
@@ -0,0 +1,37 @@
import Kredits from '../kredits';
import { fromBytes32 } from '../utils/multihash';
export default class Base {
constructor(contract) {
this.contract = contract;
}
get functions() {
return this.contract.functions;
}
// TODO: move into utils
fetchAndMergeIpfsData(data, Serializer) {
let ipfsHash = data.ipfsHash;
if (!ipfsHash) {
return data;
}
return Kredits.ipfs
.cat(ipfsHash)
.then(Serializer.deserialize)
.then((attributes) => {
return Object.assign({}, data, attributes);
});
}
reassembleIpfsHash(data) {
let { ipfsHash: digest, hashFunction, hashSize } = data;
data.ipfsHash = fromBytes32({ digest, hashFunction, hashSize });
delete data.hashFunction;
delete data.hashSize;
return data;
}
}
+72
View File
@@ -0,0 +1,72 @@
import ethers from 'npm:ethers';
import RSVP from 'rsvp';
import Kredits from '../kredits';
import ContributorSerializer from '../serializers/contributor';
import { toBytes32 } from '../utils/multihash';
import Base from './base';
export default class Contributor extends Base {
all() {
return this.contract.functions.contributorsCount()
.then((count) => {
count = count.toNumber();
let contributors = [];
for (let id = 1; id <= count; id++) {
contributors.push(this.getById(id));
}
return RSVP.all(contributors);
});
}
getById(id) {
id = ethers.utils.bigNumberify(id);
return this.contract.functions.getContributorById(id)
.then(this.reassembleIpfsHash)
.then((data) => {
// TODO: remove as soon as the contract provides the id
data.id = id;
// TODO: rename address to account
data.address = data.account;
return data;
})
// Fetch IPFS data if available
.then((data) => {
return this.fetchAndMergeIpfsData(data, ContributorSerializer);
});
}
add(attributes) {
console.log(attributes);
let json = ContributorSerializer.serialize(attributes);
// TODO: validate against schema
return Kredits.ipfs
.add(new Kredits.ipfs.Buffer(json))
.then((res) => res[0].hash)
.then((ipfsHash) => {
Object.assign(attributes, toBytes32(ipfsHash));
return attributes;
})
.then((attributes) => {
let { address, digest, hashFunction, hashSize, isCore } = attributes;
let contributor = [
address,
digest,
hashFunction,
hashSize,
isCore,
];
console.log('[kredits] addContributor', ...contributor);
return this.contract.functions.addContributor(...contributor);
});
}
}
+9
View File
@@ -0,0 +1,9 @@
import Contributor from './contributor';
import Operator from './operator';
import Token from './token';
export default {
Contributors: Contributor,
Operator,
Token
};
+72
View File
@@ -0,0 +1,72 @@
import ethers from 'npm:ethers';
import RSVP from 'rsvp';
import Kredits from '../kredits';
import ContributionSerializer from '../serializers/contribution';
import { toBytes32 } from '../utils/multihash';
import Base from './base';
export default class Operator extends Base {
all() {
return this.contract.functions.proposalsCount()
.then((count) => {
count = count.toNumber();
let proposals = [];
for (let id = 0; id < count; id++) {
proposals.push(this.getById(id));
}
return RSVP.all(proposals);
});
}
getById(id) {
id = ethers.utils.bigNumberify(id);
return this.contract.functions.proposals(id)
.then(this.reassembleIpfsHash)
.then((data) => {
// TODO: remove as soon as the contract provides the id
data.id = id;
// TODO: rename creatorAddress to creator
data.creatorAddress = data.creator;
return data;
})
// Fetch IPFS data if available
.then((data) => {
return this.fetchAndMergeIpfsData(data, ContributionSerializer);
});
}
addProposal(attributes) {
console.log(attributes);
let json = ContributionSerializer.serialize(attributes);
// TODO: validate against schema
return Kredits.ipfs
.add(new Kredits.ipfs.Buffer(json))
.then((res) => res[0].hash)
.then((ipfsHash) => {
Object.assign(attributes, toBytes32(ipfsHash));
return attributes;
})
.then((attributes) => {
let { recipientId, amount, digest, hashFunction, hashSize } = attributes;
let proposal = [
recipientId,
amount,
digest,
hashFunction,
hashSize,
];
console.log('[kredits] addProposal', ...proposal);
return this.contract.functions.addProposal(...proposal);
});
}
}
+4
View File
@@ -0,0 +1,4 @@
import Base from './base';
export default class Token extends Base {
}
+1 -10
View File
@@ -1,10 +1 @@
import ContributionSerializer from './serializers/contribution';
import ContributorSerializer from './serializers/contributor';
import { fromBytes32, toBytes32 } from './utils/multihash';
export {
ContributionSerializer,
ContributorSerializer,
fromBytes32,
toBytes32
};
export { default } from './kredits';
+77
View File
@@ -0,0 +1,77 @@
import ethers from 'npm:ethers';
import ipfsAPI from 'npm:ipfs-api';
import RSVP from 'rsvp';
import abis from 'contracts/abis';
import addresses from 'contracts/addresses';
import contracts from './contracts';
// Helpers
function capitalize(word) {
let [first, ...rest] = word;
return `${first.toUpperCase()}${rest.join('')}`;
}
export default class Kredits {
constructor(provider, signer, addresses) {
this.provider = provider;
this.signer = signer;
// Initialize our registry contract
this.addresses = addresses;
this.contracts = {};
}
static setup(provider, signer, ipfsConfig) {
this.ipfsConfig = ipfsConfig;
this.ipfs = ipfsAPI(ipfsConfig);
let registryContract = this.initRegistryContract(provider);
let addresses = Object.keys(contracts).reduce((mem, name) => {
let contractName = capitalize(name);
mem[contractName] = registryContract.functions.getProxyFor(contractName);
return mem;
}, {});
return RSVP.hash(addresses)
.then((addresses) => {
return new Kredits(provider, signer, addresses);
});
}
static initRegistryContract(provider) {
let address = addresses['Registry'][provider.chainId];
let abi = abis['Registry'];
console.log('Initialize registry contract:', address, abi, provider);
return new ethers.Contract(address, abi, provider);
}
get Contributor() {
// TODO: rename to contributor
return this.contractFor('contributors');
}
get Operator() {
return this.contractFor('operator');
}
get Token() {
return this.contractFor('token');
}
// Should be private
contractFor(name) {
if (this.contracts[name]) {
return this.contracts[name];
}
let contractName = capitalize(name);
let address = this.addresses[contractName];
let contract = new ethers.Contract(address, abis[contractName], this.signer);
this.contracts[name] = new contracts[contractName](contract);
return this.contracts[name];
}
}
+1 -1
View File
@@ -18,7 +18,7 @@ export default class Contributor {
description,
details,
url,
} = JSON.parse(serialized);
} = JSON.parse(serialized.toString('utf8'));
return {
kind,
+1 -1
View File
@@ -18,7 +18,7 @@ export default class Contributor {
kind,
url,
accounts,
} = JSON.parse(serialized);
} = JSON.parse(serialized.toString('utf8'));
let github_username, github_uid, wiki_username;
let github = accounts.find((a) => a.site === 'github.com');
+1 -1
View File
@@ -7,7 +7,7 @@ export default Route.extend({
beforeModel(transition) {
const kredits = this.get('kredits');
return kredits.initEthProvider().then(() => {
return kredits.setup().then(() => {
if (kredits.get('accountNeedsUnlock')) {
if (confirm('It looks like you have an Ethereum wallet available. Please unlock your account.')) {
transition.retry();
+1 -2
View File
@@ -9,8 +9,7 @@ export default Ember.Route.extend({
newContributor.set('kind', 'person');
let kredits = this.get('kredits');
let totalSupply = kredits.get('tokenContract')
.then((contract) => contract.totalSupply());
let totalSupply = kredits.get('kredits').Token.functions.totalSupply();
return Ember.RSVP.hash({
contributors: kredits.getContributors(),
-34
View File
@@ -1,34 +0,0 @@
import Ember from 'ember';
import ipfsAPI from 'npm:ipfs-api';
import config from 'kredits-web/config/environment';
export default Ember.Service.extend({
ipfsInstance: null,
ipfs: function() {
if (this.get('ipfsInstance')) {
return this.get('ipfsInstance');
}
let ipfs = ipfsAPI(config.ipfs);
this.set('ipfsInstance', ipfs);
return ipfs;
}.property('ipfsInstance'),
storeFile(content) {
let ipfs = this.get('ipfs');
return ipfs.add(new ipfs.Buffer(content)).then(res => {
Ember.Logger.debug('[ipfs] stored content in IPFS', content, res[0].hash);
return res[0].hash;
});
},
getFile(hash) {
return this.get('ipfs').cat(hash).then(res => {
return res.toString('utf8');
}, err => {
Ember.Logger.warn('[ipfs] error trying to fetch file', hash, err);
});
}
});
+60 -262
View File
@@ -1,36 +1,21 @@
import ethers from 'npm:ethers';
import Kredits from 'kredits-web/lib/kredits';
import RSVP from 'rsvp';
import Ember from 'ember';
import Service from 'ember-service';
import injectService from 'ember-service/inject';
import computed, { alias } from 'ember-computed';
import { isEmpty, isPresent } from 'ember-utils';
import config from 'kredits-web/config/environment';
import abis from 'contracts/abis';
import addresses from 'contracts/addresses';
import {
ContributionSerializer,
ContributorSerializer,
fromBytes32,
toBytes32
} from 'kredits-web/lib/kredits';
const {
getOwner,
Logger: {
debug,
error
debug
}
} = Ember;
export default Service.extend({
ipfs: injectService(),
ethProvider: null,
currentUserAccounts: null, // default to not having an account. this is the wen web3 is loaded.
currentUser: null,
@@ -48,7 +33,7 @@ export default Service.extend({
// this is called called in the routes beforeModel(). So it is initialized before everything else
// and we can rely on the ethProvider and the potential currentUserAccounts to be available
initEthProvider: function() {
return new Ember.RSVP.Promise((resolve) => {
return new RSVP.Promise((resolve) => {
let ethProvider;
let networkId;
if (typeof window.web3 !== 'undefined') {
@@ -58,14 +43,7 @@ export default Service.extend({
ethProvider.listAccounts().then((accounts) => {
this.set('currentUserAccounts', accounts);
this.set('ethProvider', ethProvider);
if (accounts.length > 0) {
this.get('getCurrentUser').then((contributorData) => {
this.set('currentUser', contributorData);
resolve(ethProvider);
});
} else {
resolve(ethProvider);
}
resolve(ethProvider);
});
} else {
debug('[kredits] Creating new instance from npm module class');
@@ -79,36 +57,24 @@ export default Service.extend({
});
},
registryContract: computed('ethProvider', function() {
let networkId = this.get('ethProvider').chainId;
let registry = new ethers.Contract(
addresses['Registry'][networkId],
abis['Registry'],
this.get('ethProvider')
);
return registry;
}),
setup() {
return this.initEthProvider().then((ethProvider) => {
let signer = ethProvider.getSigner();
return Kredits.setup(ethProvider, signer, config.ipfs).then((kredits) => {
this.set('kredits', kredits);
contributorsContract: computed('ethProvider', function() {
return this.contractFor('Contributors');
}),
kreditsContract: computed('ethProvider', function() {
return this.contractFor('Operator');
}),
tokenContract: computed('ethProvider', function() {
return this.contractFor('Token');
}),
contractFor(name) {
return this.get('registryContract').functions.getProxyFor(name)
.then((address) => {
debug('[kredits] get contract', name, address);
return new ethers.Contract(address, abis[name], this.get('ethProvider').getSigner());
});
// TODO: Cleanup
if (this.get('currentUserAccounts').length > 0) {
this.get('getCurrentUser').then((contributorData) => {
this.set('currentUser', contributorData);
});
}
return kredits;
});
});
},
// TODO: Only assign valid attributes
buildModel(name, attributes) {
debug('[kredits] build', name, attributes);
let model = getOwner(this).lookup(`model:${name}`);
@@ -122,237 +88,69 @@ export default Service.extend({
return model;
},
getContributorById(id) {
id = ethers.utils.bigNumberify(id);
return this.get('contributorsContract')
.then((contract) => contract.getContributorById(id))
.then(this.reassembleIpfsHash)
// Set basic data
.then(({ account: address, balance, ipfsHash, isCore }) => {
let isCurrentUser = this.get('currentUserAccounts').includes(address);
return {
id: id,
address,
balance: balance.toNumber(),
ipfsHash,
isCore,
isCurrentUser,
};
})
// Fetch IPFS data if available
.then((data) => {
return this.fetchAndMergeIpfsData(data, ContributorSerializer);
})
.then((attributes) => {
return this.buildModel('contributor', attributes);
});
},
getContributors() {
return this.get('contributorsContract')
.then((contract) => contract.contributorsCount())
.then((count) => {
count = count.toNumber();
debug('[kredits] contributors count:', count);
let contributors = [];
for(var id = 1; id <= count; id++) {
contributors.push(this.getContributorById(id));
}
return RSVP.all(contributors);
});
},
reassembleIpfsHash(data) {
let { ipfsHash: digest, hashFunction, hashSize } = data;
data.ipfsHash = fromBytes32({ digest, hashFunction, hashSize });
delete data.hashFunction;
delete data.hashSize;
return data;
},
/**
* Loads the contributor's profile data from IPFS and returns the attributes
*
* @method
* @public
*/
fetchAndMergeIpfsData(data, Serializer) {
let ipfsHash = data.ipfsHash;
if (!ipfsHash) {
return data;
}
return this.get('ipfs')
.getFile(ipfsHash)
.then(Serializer.deserialize)
.then((attributes) => {
debug('[kredits] fetched ipfs data:', attributes);
return Object.assign({}, data, attributes);
})
.catch((err) => {
error('[kredits] error trying to fetch', ipfsHash, err);
});
},
getProposalById(id) {
id = ethers.utils.bigNumberify(id);
return this.get('kreditsContract')
.then((contract) => contract.proposals(id))
.then(this.reassembleIpfsHash)
// Set basic data
.then(({
creator: creatorAddress,
recipientId,
votesCount,
votesNeeded,
amount,
executed,
ipfsHash,
}) => {
return {
id: id,
creatorAddress,
recipientId: recipientId.toString(),
votesCount: votesCount.toNumber(),
votesNeeded: votesNeeded.toNumber(),
amount: amount.toNumber(),
executed,
ipfsHash
};
})
// Fetch IPFS data if available
.then((data) => {
return this.fetchAndMergeIpfsData(data, ContributionSerializer);
})
.then((attributes) => {
return this.buildModel('proposal', attributes);
});
},
getProposals() {
return this.get('kreditsContract')
.then((contract) => contract.proposalsCount())
.then((count) => {
count = count.toNumber();
debug('[kredits] proposals count:', count);
let proposals = [];
for(var i = 0; i < count; i++) {
proposals.push(this.getProposalById(i));
}
return RSVP.all(proposals);
});
},
vote(proposalId) {
debug('[kredits] vote for', proposalId);
return this.get('kreditsContract')
.then((contract) => contract.vote(proposalId))
.then((data) => {
debug('[kredits] vote response', data);
return data;
});
},
// TODO: extract common logic to module
addContributor(attributes) {
debug('[kredits] add contributor', attributes);
let json = ContributorSerializer.serialize(attributes);
// TODO: validate against schema
return this.get('ipfs')
.storeFile(json)
// Set ipfsHash
.then((ipfsHash) => {
attributes.ipfsHash = ipfsHash;
return attributes;
})
.then((attributes) => {
return this.get('contributorsContract')
.then((contract) => {
let { address, isCore, ipfsHash } = attributes;
let { digest, hashFunction, hashSize } = toBytes32(ipfsHash);
let contributor = [
address,
digest,
hashFunction,
hashSize,
isCore,
];
debug('[kredits] addContributor', ...contributor);
return contract.addContributor(...contributor);
});
})
return this.get('kredits').Contributor.add(attributes)
.then((data) => {
debug('[kredits] add contributor response', data);
return this.buildModel('contributor', attributes);
});
},
getContributors() {
return this.get('kredits').Contributor.all()
.then((contributors) => {
return contributors.map((contributor) => {
return this.buildModel('contributor', contributor);
});
});
},
addProposal(attributes) {
debug('[kredits] add proposal', attributes);
let json = ContributionSerializer.serialize(attributes);
// TODO: validate against schema
return this.get('ipfs')
.storeFile(json)
// Set ipfsHash
.then((ipfsHash) => {
delete attributes.contributorIpfsHash;
attributes.ipfsHash = ipfsHash;
return attributes;
})
.then((attributes) => {
return this.get('kreditsContract')
.then((contract) => {
let { recipientId, amount, ipfsHash } = attributes;
let { digest, hashFunction, hashSize } = toBytes32(ipfsHash);
let proposal = [
recipientId,
amount,
digest,
hashFunction,
hashSize,
];
debug('[kredits] addProposal', ...proposal);
return contract.addProposal(...proposal);
});
})
return this.get('kredits').Operator.addProposal(attributes)
.then((data) => {
debug('[kredits] add proposal response', data);
return this.buildModel('proposal', attributes);
});
},
getProposals() {
return this.get('kredits').Operator.all()
.then((proposals) => {
return proposals.map((proposal) => {
return this.buildModel('proposal', proposal);
});
});
},
vote(proposalId) {
debug('[kredits] vote for', proposalId);
return this.get('kredits').Operator.functions.vote(proposalId)
.then((data) => {
debug('[kredits] vote response', data);
return data;
});
},
// TODO: Cleanup
getCurrentUser: computed('ethProvider', function() {
if (isEmpty(this.get('currentUserAccounts'))) {
return RSVP.resolve();
}
return this.get('contributorsContract')
.then((contract) => {
return contract.getContributorIdByAddress(this.get('currentUserAccounts.firstObject'))
.then((id) => {
id = id.toNumber();
// check if the user is a contributor or not
if (id === 0) {
return RSVP.resolve();
} else {
return this.getContributorById(id);
}
});
return this.get('kredits').Contributor
.functions.getContributorIdByAddress(this.get('currentUserAccounts.firstObject'))
.then((id) => {
id = id.toNumber();
// check if the user is a contributor or not
if (id === 0) {
return RSVP.resolve();
} else {
return this.get('kredits').Contributor.getById(id);
}
});
})
});
+1 -1
View File
@@ -68,7 +68,7 @@
</header>
<div class="content">
{{#if currentUser.isCore}}
{{#if kredits.currentUser.isCore}}
{{add-contributor contributors=model.contributors save=(action 'save')}}
{{else}}
Only core team members can add new contributors. Please ask someone to set you up.