Merge pull request #57 from 67P/use-kredits-npm-lib

Remove kredits library files and use npm package
This commit was merged in pull request #57.
This commit is contained in:
2018-04-18 22:50:41 +00:00
committed by GitHub
17 changed files with 853 additions and 1816 deletions
-17
View File
@@ -1,17 +0,0 @@
export default class Base {
constructor(contract) {
this.contract = contract;
}
get functions() {
return this.contract.functions;
}
on(type, callback) {
let eventMethod = `on${type.toLowerCase()}`;
// Don't use this.contract.events here. Seems to be a bug in ethers.js
this.contract[eventMethod] = callback;
return this;
}
}
-58
View File
@@ -1,58 +0,0 @@
import ethers from 'npm:ethers';
import RSVP from 'rsvp';
import Kredits from '../kredits';
import ContributorSerializer from '../serializers/contributor';
import Base from './base';
export default class Contributor extends Base {
all() {
return this.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.functions.getContributorById(id)
.then((data) => {
// TODO: remove when naming updated on the contract
data.hashDigest = data.ipfsHash;
return data;
})
// Fetch IPFS data if available
.then((data) => {
return Kredits.ipfs.catAndMerge(data, ContributorSerializer.deserialize);
});
}
add(contributorAttr) {
let json = ContributorSerializer.serialize(contributorAttr);
// TODO: validate against schema
return Kredits.ipfs
.add(json)
.then((ipfsHashAttr) => {
let contributor = [
contributorAttr.address,
ipfsHashAttr.hashDigest,
ipfsHashAttr.hashFunction,
ipfsHashAttr.hashSize,
contributorAttr.isCore,
];
console.log('[kredits] addContributor', ...contributor);
return this.functions.addContributor(...contributor);
});
}
}
-9
View File
@@ -1,9 +0,0 @@
import Contributor from './contributor';
import Operator from './operator';
import Token from './token';
export default {
Contributors: Contributor,
Operator,
Token
};
-58
View File
@@ -1,58 +0,0 @@
import ethers from 'npm:ethers';
import RSVP from 'rsvp';
import Kredits from '../kredits';
import ContributionSerializer from '../serializers/contribution';
import Base from './base';
export default class Operator extends Base {
all() {
return this.functions.proposalsCount()
.then((count) => {
count = count.toNumber();
let proposals = [];
for (let id = 1; id <= count; id++) {
proposals.push(this.getById(id));
}
return RSVP.all(proposals);
});
}
getById(id) {
id = ethers.utils.bigNumberify(id);
return this.functions.getProposal(id)
.then((data) => {
// TODO: remove when naming updated on the contract
data.hashDigest = data.ipfsHash;
return data;
})
// Fetch IPFS data if available
.then((data) => {
return Kredits.ipfs.catAndMerge(data, ContributionSerializer.deserialize);
});
}
addProposal(proposalAttr) {
let json = ContributionSerializer.serialize(proposalAttr);
// TODO: validate against schema
return Kredits.ipfs
.add(json)
.then((ipfsHashAttr) => {
let proposal = [
proposalAttr.contributorId,
proposalAttr.amount,
ipfsHashAttr.hashDigest,
ipfsHashAttr.hashFunction,
ipfsHashAttr.hashSize,
];
console.log('[kredits] addProposal', ...proposal);
return this.functions.addProposal(...proposal);
});
}
}
-4
View File
@@ -1,4 +0,0 @@
import Base from './base';
export default class Token extends Base {
}
-1
View File
@@ -1 +0,0 @@
export { default } from './kredits';
-102
View File
@@ -1,102 +0,0 @@
import ethers from 'npm:ethers';
import RSVP from 'rsvp';
import abis from 'contracts/abis';
import addresses from 'contracts/addresses';
import contracts from './contracts';
import IPFS from './utils/ipfs';
// 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 = new IPFS(ipfsConfig);
return this.ipfs._ipfsAPI.id().catch((error) => {
throw new Error(`IPFS node not available; config: ${JSON.stringify(ipfsConfig)} - ${error.message}`);
}).then(() => {
let registryContract = this.initRegistryContract(provider);
let addresses = Object.keys(contracts).reduce((mem, name) => {
let contractName = capitalize(name);
mem[contractName] = registryContract.functions.getProxyFor(contractName).catch((error) => {
throw new Error(`Failed to get address for ${contractName} from registry at ${registryContract.address}
- correct registry? does it have version entry? - ${error.message}`
);
});
return mem;
}, {});
return RSVP.hash(addresses)
.then((addresses) => {
return new Kredits(provider, signer, addresses);
});
});
}
static initRegistryContract(provider) {
let address = addresses['Registry'][provider.chainId];
if (!address) {
throw new Error(`Registry address not found; invalid network?
requested network: ${provider.chainId}
supported networks: ${Object.keys(addresses['Registry'])}
`);
}
provider.getCode(address).then((code) => {
// not sure if we always get the same return value of the code is not available
// that's why checking if it is < 5 long
if (code === '0x00' || code.length < 5) {
throw new Error(`Registry not found at ${address} on network ${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];
if (!address || !abis[contractName]) {
throw new Error(`Address or ABI not found for ${contractName}`);
}
let contract = new ethers.Contract(address, abis[contractName], this.signer);
this.contracts[name] = new contracts[contractName](contract);
return this.contracts[name];
}
}
@@ -1,64 +0,0 @@
/**
* Handle serialization for JSON-LD object of the contribution, according to
* https://github.com/67P/kosmos-schemas/blob/master/schemas/contribution.json
*
* @class
* @public
*/
export default class Contributor {
/**
* Deserialize JSON to object
*
* @method
* @public
*/
static deserialize(serialized) {
let {
kind,
description,
details,
url,
} = JSON.parse(serialized.toString('utf8'));
return {
kind,
description,
details,
url,
ipfsData: serialized,
};
}
/**
* Serialize object to JSON
*
* @method
* @public
*/
static serialize(deserialized) {
let {
contributorIpfsHash,
kind,
description,
url,
} = deserialized;
let data = {
"@context": "https://schema.kosmos.org",
"@type": "Contribution",
"contributor": {
"ipfs": contributorIpfsHash
},
kind,
description,
"details": {}
};
if (url) {
data["url"] = url;
}
// Write it pretty to ipfs
return JSON.stringify(data, null, 2);
}
}
@@ -1,93 +0,0 @@
/**
* Handle serialization for JSON-LD object of the contributor, according to
* https://github.com/67P/kosmos-schemas/blob/master/schemas/contributor.json
*
* @class
* @public
*/
export default class Contributor {
/**
* Deserialize JSON to object
*
* @method
* @public
*/
static deserialize(serialized) {
let {
name,
kind,
url,
accounts,
} = JSON.parse(serialized.toString('utf8'));
let github_username, github_uid, wiki_username;
let github = accounts.find((a) => a.site === 'github.com');
let wiki = accounts.find((a) => a.site === 'wiki.kosmos.org');
if (github) {
(({ username: github_username, uid: github_uid} = github));
}
if (wiki) {
(({ username: wiki_username } = wiki));
}
return {
name,
kind,
url,
github_uid,
github_username,
wiki_username,
ipfsData: serialized,
};
}
/**
* Serialize object to JSON
*
* @method
* @public
*/
static serialize(deserialized) {
let {
name,
kind,
url,
github_uid,
github_username,
wiki_username,
} = deserialized;
let data = {
"@context": "https://schema.kosmos.org",
"@type": "Contributor",
kind,
name,
"accounts": []
};
if (url) {
data["url"] = url;
}
if (github_uid) {
data.accounts.push({
"site": "github.com",
"uid": github_uid,
"username": github_username,
"url": `https://github.com/${github_username}`
});
}
if (wiki_username) {
data.accounts.push({
"site": "wiki.kosmos.org",
"username": wiki_username,
"url": `https://wiki.kosmos.org/User:${wiki_username}`
});
}
// Write it pretty to ipfs
return JSON.stringify(data, null, 2);
}
}
-57
View File
@@ -1,57 +0,0 @@
import ipfsAPI from 'npm:ipfs-api';
import multihashes from 'npm:multihashes';
export default class IPFS {
constructor(config) {
this._ipfsAPI = ipfsAPI(config);
this._config = config;
}
catAndMerge(data, deserialize) {
// if no hash details are found simply return the data; nothing to merge
if (!data.hashSize || data.hashSize === 0) {
return data;
}
// merge ipfsHash (encoded from hashDigest, hashSize, hashFunction)
data.ipfsHash = this.encodeHash(data);
return this.cat(data)
.then(deserialize)
.then((attributes) => {
return Object.assign({}, data, attributes);
});
}
add(data) {
return this._ipfsAPI
.add(new this._ipfsAPI.Buffer(data))
.then((res) => {
return this.decodeHash(res[0].hash);
});
}
cat(hashData) {
let ipfsHash = hashData; // default - if it is a string
if (hashData.hasOwnProperty('hashSize')) {
ipfsHash = this.encodeHash(hashData);
}
return this._ipfsAPI.cat(ipfsHash);
}
decodeHash(ipfsHash) {
let multihash = multihashes.decode(multihashes.fromB58String(ipfsHash));
return {
hashDigest: '0x' + multihashes.toHexString(multihash.digest),
hashSize: multihash.length,
hashFunction: multihash.code,
ipfsHash: ipfsHash
};
}
encodeHash(hashData) {
let digest = this._ipfsAPI.Buffer.from(hashData.hashDigest.slice(2), 'hex');
return multihashes.encode(digest, hashData.hashFunction, hashData.hashSize);
}
}
+1 -1
View File
@@ -3,7 +3,7 @@ import { computed } from '@ember/object';
import { alias } from '@ember/object/computed';
import { isEmpty, isPresent } from '@ember/utils';
import RSVP from 'rsvp';
import Kredits from 'kredits-web/lib/kredits';
import Kredits from 'npm:kredits-contracts';
import Contributor from 'kredits-web/models/contributor'
import Proposal from 'kredits-web/models/proposal'
import ethers from 'npm:ethers';
-32
View File
@@ -1,32 +0,0 @@
/*jshint node:true*/
const writeFile = require('broccoli-file-creator');
const mergeTrees = require('broccoli-merge-trees');
const jsonModule = require('broccoli-json-module');
module.exports = {
name: 'contracts',
treeForAddon: function(tree) {
let trees = [];
const files = require('kredits-contracts/lib');
let abis = {};
let addresses = {};
files.forEach(function(file) {
abis[file] = require(`kredits-contracts/lib/abis/${file}.json`);
addresses[file] = require(`kredits-contracts/lib/addresses/${file}.json`);
});
trees.push(writeFile(`abis/index.json`, JSON.stringify(abis)));
trees.push(writeFile(`addresses/index.json`, JSON.stringify(addresses)));
tree = jsonModule(mergeTrees(trees));
return this._super.treeForAddon.call(this, tree);
},
isDevelopingAddon: function() {
return true;
}
};
-6
View File
@@ -1,6 +0,0 @@
{
"name": "contracts",
"keywords": [
"ember-addon"
]
}
+848 -1299
View File
File diff suppressed because it is too large Load Diff
+2 -13
View File
@@ -23,11 +23,6 @@
"babel-preset-es2015": "^6.22.0",
"babelify": "^7.3.0",
"broccoli-asset-rev": "^2.4.5",
"broccoli-file-creator": "^1.1.1",
"broccoli-json-module": "^1.0.0",
"broccoli-merge-trees": "^3.0.0",
"bs58": "^4.0.1",
"buffer": "^5.1.0",
"ember-ajax": "^3.0.0",
"ember-awesome-macros": "0.41.0",
"ember-browserify": "^1.1.13",
@@ -54,9 +49,8 @@
"ember-truth-helpers": "github:jmurphyau/ember-truth-helpers#31a14373a31f1f82c77537720549b47a95c28e5f",
"eslint-plugin-ember": "^5.0.0",
"ethers": "^3.0.8",
"ipfs-api": "^19.0.0",
"kosmos-schemas": "^1.1.2",
"kredits-contracts": "github:67P/truffle-kredits#master",
"kredits-contracts": "github:67P/truffle-kredits",
"loader.js": "^4.2.3",
"tv4": "^1.3.0"
},
@@ -67,10 +61,5 @@
"Garret Alfert <alfert@wevelop.de>",
"Sebastian Kippe <sebastian@kip.pe>",
"Michael Bumann <hello@michaelbumann.com>"
],
"ember-addon": {
"paths": [
"lib/contracts"
]
}
]
}
@@ -1,7 +1,7 @@
import { module, test } from 'qunit';
import schemas from 'npm:kosmos-schemas';
import tv4 from 'npm:tv4';
import ContributionSerializer from 'kredits-web/lib/kredits/serializers/contribution';
import ContributionSerializer from 'npm:kredits-contracts/lib/serializers/contribution';
module('Serializers contribution', function() {
test('#serialize returns a valid JSON-LD representation', function(assert) {
@@ -1,7 +1,7 @@
import { module, test } from 'qunit';
import schemas from 'npm:kosmos-schemas';
import tv4 from 'npm:tv4';
import ContributorSerializer from 'kredits-web/lib/kredits/serializers/contributor';
import ContributorSerializer from 'npm:kredits-contracts/lib/serializers/contributor';
module('Serializers contributor', function() {
test('#serialize returns a valid JSON-LD representation', function(assert) {