Fix services

This commit is contained in:
Lyubomir Kiprov 2019-05-17 13:59:46 +03:00
parent 5e72cc248c
commit a9e1df90bc
18 changed files with 248 additions and 277 deletions

View File

@ -109,7 +109,7 @@ module.exports = {
testnet: { testnet: {
deployment: { deployment: {
accounts: [{ mnemonic: wallet.mnemonic }], accounts: [{ mnemonic: wallet.mnemonic }],
host: `ropsten.infura.io/v3/`, host: `ropsten.infura.io/v3/8675214b97b44e96b70d05326c61fd6a`,
port: false, port: false,
type: 'rpc', type: 'rpc',
protocol: 'https', protocol: 'https',

View File

@ -1,2 +1,2 @@
module.exports.mnemonic = module.exports.mnemonic =
'artefact rebuild liquid honey sport clean candy motor cereal job gap series' ''

View File

@ -2,27 +2,27 @@ module.exports = {
// default applies to all environments // default applies to all environments
default: { default: {
enabled: true, enabled: true,
ipfs_bin: "ipfs", ipfs_bin: 'ipfs',
available_providers: ["ipfs"], provider: 'ipfs',
available_providers: ['ipfs'],
upload: { upload: {
provider: "ipfs", host: 'localhost',
host: "localhost", port: 5001,
port: 5001
}, },
dappConnection: [ dappConnection: [
{ {
provider: "ipfs", provider: 'ipfs',
host: "localhost", host: 'localhost',
port: 5001, port: 5001,
getUrl: "http://localhost:8080/ipfs/" getUrl: 'http://localhost:8080/ipfs/',
} },
] ],
// Configuration to start Swarm in the same terminal as `embark run` // Configuration to start Swarm in the same terminal as `embark run`
/*,account: { /* ,account: {
address: "YOUR_ACCOUNT_ADDRESS", // Address of account accessing Swarm address: "YOUR_ACCOUNT_ADDRESS", // Address of account accessing Swarm
password: "PATH/TO/PASSWORD/FILE" // File containing the password of the account password: "PATH/TO/PASSWORD/FILE" // File containing the password of the account
}, },
swarmPath: "PATH/TO/SWARM/EXECUTABLE" // Path to swarm executable (default: swarm)*/ swarmPath: "PATH/TO/SWARM/EXECUTABLE" // Path to swarm executable (default: swarm) */
}, },
// default environment, merges with the settings in default // default environment, merges with the settings in default
@ -30,30 +30,45 @@ module.exports = {
development: { development: {
enabled: true, enabled: true,
upload: { upload: {
provider: "ipfs", provider: 'ipfs',
host: "localhost", host: 'localhost',
port: 5001, port: 5001,
getUrl: "http://localhost:8080/ipfs/" getUrl: 'http://localhost:8080/ipfs/',
} },
}, },
// merges with the settings in default // merges with the settings in default
// used with "embark run privatenet" // used with "embark run privatenet"
privatenet: { privatenet: {},
},
// merges with the settings in default // merges with the settings in default
// used with "embark run testnet" // used with "embark run testnet"
testnet: { testnet: {
enabled: true,
ipfs_bin: 'ipfs',
provider: 'ipfs',
available_providers: ['ipfs'],
upload: {
host: 'localhost',
port: 5001,
},
dappConnection: [
{
provider: 'ipfs',
protocol: 'https',
host: 'ipfs.infura.io',
port: 5001,
getUrl: 'https://ipfs.infura.io/ipfs/',
},
],
}, },
// merges with the settings in default // merges with the settings in default
// used with "embark run livenet" // used with "embark run livenet"
livenet: { livenet: {},
},
// you can name an environment with specific settings and then specify with // you can name an environment with specific settings and then specify with
// "embark run custom_name" // "embark run custom_name"
//custom_name: { // custom_name: {
//} // }
}; }

View File

@ -93,9 +93,7 @@ contract Discover is ApproveAndCallFallBack, BancorFormula {
* @param _amount uint, included for approveAndCallFallBack * @param _amount uint, included for approveAndCallFallBack
*/ */
function downvote(bytes32 _id, uint _amount) external { function downvote(bytes32 _id, uint _amount) external {
(,,uint c) = downvoteCost(_id); _downvote(msg.sender, _id, _amount);
require(_amount == c, "Incorrect amount: valid iff effect on ranking is 1%");
_downvote(msg.sender, _id, c);
} }
/** /**

View File

@ -1,28 +1,48 @@
/* global web3 */
import utils from './utils' import utils from './utils'
import EmbarkJS from '../../embarkArtifacts/embarkjs'
import * as IPFSService from './ipfs'
import SNTService from './services/contracts-services/snt-service/snt-service' import SNTService from './services/contracts-services/snt-service/snt-service'
import DiscoverService from './services/contracts-services/discover-service/discover-service' import DiscoverService from './services/contracts-services/discover-service/discover-service'
import BlockchainConfig from './services/config' const initServices = function() {
const sharedContext = {
account: '0x0000000000000000000000000000000000000000',
}
const init = function() { sharedContext.SNTService = new SNTService(sharedContext)
try { sharedContext.DiscoverService = new DiscoverService(sharedContext)
BlockchainConfig()
const sharedContext = { return {
account: '', IPFSService,
} SNTService: sharedContext.SNTService,
DiscoverService: sharedContext.DiscoverService,
sharedContext.SNTService = new SNTService(sharedContext) utils,
sharedContext.DiscoverService = new DiscoverService(sharedContext)
return {
SNTService: sharedContext.SNTService,
DiscoverService: sharedContext.DiscoverService,
utils,
}
} catch (error) {
throw new Error(error.message)
} }
} }
export default { init, utils } const getInstance = async () => {
return new Promise((resolve, reject) => {
const returnInstance = () => {
try {
const services = initServices()
resolve(services)
} catch (error) {
reject(error.message)
}
}
if (web3.currentProvider) {
returnInstance()
} else {
EmbarkJS.onReady(err => {
if (err) reject(err)
returnInstance()
})
}
})
}
export default { getInstance, utils }

View File

@ -1,8 +1,8 @@
import * as helpers from './helpers' import * as helpers from './helpers'
import EmbarkJSService from '../services/embark-service/embark-service' import EmbarkJS from '../../../embarkArtifacts/embarkjs'
const checkIPFSAvailability = async () => { const checkIPFSAvailability = async () => {
const isAvailable = await EmbarkJSService.Storage.isAvailable() const isAvailable = await EmbarkJS.Storage.isAvailable()
if (!isAvailable) { if (!isAvailable) {
throw new Error('IPFS Storage is unavailable') throw new Error('IPFS Storage is unavailable')
} }
@ -15,11 +15,11 @@ const uploadImage = async base64Image => {
}, },
] ]
return EmbarkJSService.Storage.uploadFile(imageFile) return EmbarkJS.Storage.uploadFile(imageFile)
} }
const uploadMetadata = async metadata => { const uploadMetadata = async metadata => {
const hash = await EmbarkJSService.Storage.saveText(metadata) const hash = await EmbarkJS.Storage.saveText(metadata)
return helpers.getBytes32FromIpfsHash(hash) return helpers.getBytes32FromIpfsHash(hash)
} }
@ -40,11 +40,11 @@ export const uploadDAppMetadata = async metadata => {
const retrieveMetadata = async metadataBytes32 => { const retrieveMetadata = async metadataBytes32 => {
const metadataHash = helpers.getIpfsHashFromBytes32(metadataBytes32) const metadataHash = helpers.getIpfsHashFromBytes32(metadataBytes32)
return EmbarkJSService.Storage.get(metadataHash) return EmbarkJS.Storage.get(metadataHash)
} }
const retrieveImageUrl = async imageHash => { const retrieveImageUrl = async imageHash => {
return EmbarkJSService.Storage.getUrl(imageHash) return EmbarkJS.Storage.getUrl(imageHash)
} }
export const retrieveDAppMetadataByHash = async metadataBytes32 => { export const retrieveDAppMetadataByHash = async metadataBytes32 => {

View File

@ -1,9 +0,0 @@
/* global web3 */
import Web3 from '../../../embarkArtifacts/modules/web3'
// Todo: Should be moved to .env
const RPC_URL = 'https://ropsten.infura.io/v3/'
export default function() {
web3 = new Web3(new Web3.providers.HttpProvider(RPC_URL))
}

View File

@ -1,32 +1,32 @@
/* global web3 */ /* global web3 */
import EmbarkJSService from '../embark-service/embark-service' import EmbarkJS from '../../../../embarkArtifacts/embarkjs'
const getAccount = async () => {
try {
const account = (await EmbarkJS.Blockchain.Providers.web3.getAccounts())[0]
return account || (await EmbarkJS.enableEthereum())[0]
} catch (error) {
throw new Error(
'Could not unlock an account. Consider installing Status on your mobile or Metamask extension',
)
}
}
class BlockchainService { class BlockchainService {
constructor(sharedContext, contract, Validator) { constructor(sharedContext, contract, Validator) {
this.contract = contract.address this.contract = contract.address
contract.setProvider(web3.currentProvider)
this.sharedContext = sharedContext this.sharedContext = sharedContext
this.validator = new Validator(this) this.validator = new Validator(this)
} }
async __unlockServiceAccount() { async __unlockServiceAccount() {
// const accounts = await EmbarkJS.Blockchain.Providers.web3.getAccounts() if (web3 && EmbarkJS.Blockchain.Providers.web3) {
// // if (accounts.length > 0) { this.sharedContext.account = await getAccount()
// this.sharedContext.account = accounts[0] } else {
// } else { throw new Error('web3 is missing')
// const provider = global.web3.currentProvider
// Check for undefined
// console.log(await global.web3.eth.getAccounts())
const accounts = await EmbarkJSService.enableEthereum()
if (accounts) {
this.sharedContext.account = accounts[0]
} }
// global.web3.setProvider(provider)
// }
// throw new Error('Could not unlock an account or web3 is missing')
} }
} }

View File

@ -16,30 +16,37 @@ class DiscoverService extends BlockchainService {
async upVoteEffect(id, amount) { async upVoteEffect(id, amount) {
await this.validator.validateUpVoteEffect(id, amount) await this.validator.validateUpVoteEffect(id, amount)
return DiscoverContract.methods.upvoteEffect(id, amount).call() return DiscoverContract.methods
.upvoteEffect(id, amount)
.call({ from: this.sharedContext.account })
} }
async downVoteCost(id) { async downVoteCost(id) {
const dapp = await this.getDAppById(id) const dapp = await this.getDAppById(id)
return DiscoverContract.methods.downvoteCost(dapp.id).call() return DiscoverContract.methods
.downvoteCost(dapp.id)
.call({ from: this.sharedContext.account })
} }
async getDAppsCount() { async getDAppsCount() {
return DiscoverContract.methods.getDAppsCount().call() return DiscoverContract.methods
.getDAppsCount()
.call({ from: this.sharedContext.account })
} }
async getDApps() { async getDApps() {
const dapps = [] const dapps = []
const dappsCount = await DiscoverContract.methods.getDAppsCount().call() const dappsCount = await DiscoverContract.methods
.getDAppsCount()
.call({ from: this.sharedContext.account })
try { try {
for (let i = 0; i < dappsCount; i++) { for (let i = 0; i < dappsCount; i++) {
const dapp = await DiscoverContract.methods.dapps(i).call() const dapp = await DiscoverContract.methods
.dapps(i)
.call({ from: this.sharedContext.account })
dapp.metadata = await ipfsSDK.retrieveDAppMetadataByHash(dapp.metadata) dapp.metadata = await ipfsSDK.retrieveDAppMetadataByHash(dapp.metadata)
dapps.push(dapp) dapps.push(dapp)
} }
return dapps return dapps
} catch (error) { } catch (error) {
throw new Error(`Error fetching dapps. Details: ${error.message}`) throw new Error(`Error fetching dapps. Details: ${error.message}`)
@ -49,8 +56,12 @@ class DiscoverService extends BlockchainService {
async getDAppById(id) { async getDAppById(id) {
let dapp let dapp
try { try {
const dappId = await DiscoverContract.methods.id2index(id).call() const dappId = await DiscoverContract.methods
dapp = await DiscoverContract.methods.dapps(dappId).call() .id2index(id)
.call({ from: this.sharedContext.account })
dapp = await DiscoverContract.methods
.dapps(dappId)
.call({ from: this.sharedContext.account })
} catch (error) { } catch (error) {
throw new Error('Searching DApp does not exists') throw new Error('Searching DApp does not exists')
} }
@ -74,11 +85,15 @@ class DiscoverService extends BlockchainService {
} }
async safeMax() { async safeMax() {
return DiscoverContract.methods.safeMax().call() return DiscoverContract.methods
.safeMax()
.call({ from: this.sharedContext.account })
} }
async isDAppExists(id) { async isDAppExists(id) {
return DiscoverContract.methods.existingIDs(id).call() return DiscoverContract.methods
.existingIDs(id)
.call({ from: this.sharedContext.account })
} }
// Transaction methods // Transaction methods
@ -114,10 +129,13 @@ class DiscoverService extends BlockchainService {
) )
} }
async downVote(id, amount) { async downVote(id) {
await this.validator.validateDownVoting(id, amount) const dapp = await this.getDAppById(id)
const amount = (await this.downVoteCost(dapp.id)).c
const callData = DiscoverContract.methods.downvote(id, amount).encodeABI() const callData = DiscoverContract.methods
.downvote(dapp.id, amount)
.encodeABI()
return this.sharedContext.SNTService.approveAndCall( return this.sharedContext.SNTService.approveAndCall(
this.contract, this.contract,
amount, amount,

View File

@ -41,15 +41,6 @@ class DiscoverValidator {
} }
} }
async validateDownVoting(id, amount) {
const dapp = await this.service.getDAppById(id)
const downVoteCost = await this.service.downVoteCost(dapp.id)
if (downVoteCost.c != amount) {
throw new Error('Incorrect amount: valid if effect on ranking is 1%')
}
}
async validateWithdrawing(id, amount) { async validateWithdrawing(id, amount) {
const dapp = await this.service.getDAppById(id) const dapp = await this.service.getDAppById(id)

View File

@ -11,19 +11,27 @@ class SNTService extends BlockchainService {
} }
async allowance(from, to) { async allowance(from, to) {
return SNTToken.methods.allowance(from, to).call() return SNTToken.methods
.allowance(from, to)
.call({ from: this.sharedContext.account })
} }
async balanceOf(account) { async balanceOf(account) {
return SNTToken.methods.balanceOf(account).call() return SNTToken.methods
.balanceOf(account)
.call({ from: this.sharedContext.account })
} }
async controller() { async controller() {
return SNTToken.methods.controller().call() return SNTToken.methods
.controller()
.call({ from: this.sharedContext.account })
} }
async transferable() { async transferable() {
return SNTToken.methods.transfersEnabled().call() return SNTToken.methods
.transfersEnabled()
.call({ from: this.sharedContext.account })
} }
async approveAndCall(spender, amount, callData) { async approveAndCall(spender, amount, callData) {

View File

@ -1,14 +0,0 @@
import EmbarkJS from '../../../../embarkArtifacts/embarkjs'
class EmbarkService {
constructor() {
if (!EmbarkService.instance) {
EmbarkJS.Storage.setProvider('ipfs')
EmbarkService.instance = EmbarkJS
}
return EmbarkService.instance
}
}
export default new EmbarkService()

View File

@ -3,7 +3,7 @@ import exampleImage from './dapp.image'
import BlockchainSDK from '../../common/blockchain' import BlockchainSDK from '../../common/blockchain'
const SERVICES = BlockchainSDK.init() let SERVICES = ''
const DAPP_DATA = { const DAPP_DATA = {
name: 'Test1', name: 'Test1',
@ -35,7 +35,7 @@ class Example extends React.Component {
async createDApp() { async createDApp() {
await SERVICES.SNTService.generateTokens() await SERVICES.SNTService.generateTokens()
return SERVICES.DiscoverService.createDApp(10000, DAPP_DATA) // return SERVICES.DiscoverService.createDApp(10000, DAPP_DATA)
} }
async upvote(id) { async upvote(id) {
@ -64,8 +64,9 @@ class Example extends React.Component {
} }
async logDiscoverMethods() { async logDiscoverMethods() {
console.log(await SERVICES.DiscoverService.getDApps()) SERVICES = await BlockchainSDK.getInstance()
// const createdDApp = await this.createDApp() // console.log(await SERVICES.DiscoverService.getDApps())
const createdDApp = await this.createDApp()
// const dappData = await this.getFullDApp(createdDApp.id) // const dappData = await this.getFullDApp(createdDApp.id)
// console.log(`Created DApp : ${JSON.stringify(dappData)}`) // console.log(`Created DApp : ${JSON.stringify(dappData)}`)

View File

@ -1,7 +1,7 @@
// import hardcodedDapps from '../../common/data/dapps' // import hardcodedDapps from '../../common/data/dapps'
import * as Categories from '../../common/data/categories' import * as Categories from '../../common/data/categories'
import reducerUtil from '../../common/utils/reducer' import reducerUtil from '../../common/utils/reducer'
// import BlockchainTool from '../../common/blockchain' import BlockchainSDK from '../../common/blockchain'
const ON_FINISH_FETCH_ALL_DAPPS_ACTION = 'ON_FINISH_FETCH_ALL_DAPPS_ACTION' const ON_FINISH_FETCH_ALL_DAPPS_ACTION = 'ON_FINISH_FETCH_ALL_DAPPS_ACTION'
@ -18,16 +18,6 @@ const ON_ADD_NEW_DAPP = 'ON_ADD_NEW_DAPP'
const RECENTLY_ADDED_SIZE = 50 const RECENTLY_ADDED_SIZE = 50
const HIGHEST_RANKED_SIZE = 50 const HIGHEST_RANKED_SIZE = 50
// const BlockchainSDK = BlockchainTool.init()
const BlockchainSDK = { DiscoverService: {} }
BlockchainSDK.DiscoverService.getDApps = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(hardcodedDapps)
}, 100)
})
}
class DappsState { class DappsState {
constructor() { constructor() {
this.items = [] this.items = []
@ -100,9 +90,14 @@ export const onFinishFetchByCategoryAction = (category, dapps) => ({
const fetchAllDappsInState = async (dispatch, getState) => { const fetchAllDappsInState = async (dispatch, getState) => {
const stateDapps = getState().dapps const stateDapps = getState().dapps
if (stateDapps.dapps === null) { if (stateDapps.dapps === null) {
let dapps = await BlockchainSDK.DiscoverService.getDApps() const blockchain = await BlockchainSDK.getInstance()
let dapps = await blockchain.DiscoverService.getDApps()
dapps = dapps.map(dapp => { dapps = dapps.map(dapp => {
return Object.assign(dapp.metadata, { sntValue: parseInt(dapp.rate, 10) }) return Object.assign(dapp.metadata, {
id: dapp.id,
sntValue: parseInt(dapp.effectiveBalance, 10),
})
}) })
dapps.sort((a, b) => { dapps.sort((a, b) => {
return b.sntValue - a.sntValue return b.sntValue - a.sntValue
@ -272,7 +267,7 @@ const onAddNewDapp = (state, dapp) => {
state.dappsCategoryMap.forEach((dappState, category_) => { state.dappsCategoryMap.forEach((dappState, category_) => {
dappsCategoryMap.set(category_, dappState) dappsCategoryMap.set(category_, dappState)
}) })
const dappState = dappsCategoryMap.get(dapp.metadata.category) const dappState = dappsCategoryMap.get(dapp.category)
insertDappIntoSortedArray(dappState.items, dapp, (target, dappItem) => { insertDappIntoSortedArray(dappState.items, dapp, (target, dappItem) => {
return target.sntValue < dappItem.sntValue return target.sntValue < dappItem.sntValue
}) })

View File

@ -5,16 +5,7 @@ import {
checkTransactionStatusAction, checkTransactionStatusAction,
} from '../TransactionStatus/TransactionStatus.recuder' } from '../TransactionStatus/TransactionStatus.recuder'
// import BlockchainTool from '../../common/blockchain' import BlockchainSDK from '../../common/blockchain'
// const BlockchainSDK = BlockchainTool.init()
const BlockchainSDK = { DiscoverService: {} }
BlockchainSDK.DiscoverService.createDapp = async (snt, dapp) => {
return {
tx: '0x3513rewrsdfsdf',
id: 1,
}
}
const SHOW_SUBMIT = 'SHOW_SUBMIT' const SHOW_SUBMIT = 'SHOW_SUBMIT'
const CLOSE_SUBMIT = 'CLOSE_SUBMIT' const CLOSE_SUBMIT = 'CLOSE_SUBMIT'
@ -98,7 +89,8 @@ export const onImgDoneAction = imgBase64 => ({
export const submitAction = dapp => { export const submitAction = dapp => {
return async dispatch => { return async dispatch => {
dispatch(closeSubmitAction()) dispatch(closeSubmitAction())
const { tx, id } = await BlockchainSDK.DiscoverService.createDApp(1, { const blockchain = await BlockchainSDK.getInstance()
const { tx, id } = await blockchain.DiscoverService.createDApp(1, {
name: dapp.name, name: dapp.name,
url: dapp.url, url: dapp.url,
desc: dapp.desc, desc: dapp.desc,

View File

@ -5,39 +5,13 @@ import {
transactionStatusInitInstance, transactionStatusInitInstance,
} from './TransactionStatus.utilities' } from './TransactionStatus.utilities'
import { onAddNewDappAction } from '../Dapps/Dapps.reducer' import { onAddNewDappAction } from '../Dapps/Dapps.reducer'
// import BlockchainTool from '../../common/blockchain' import BlockchainSDK from '../../common/blockchain'
const HIDE = 'HIDE' const HIDE = 'HIDE'
const ON_START_PROGRESS = 'ON_START_PROGRESS' const ON_START_PROGRESS = 'ON_START_PROGRESS'
const ON_RECEIVE_TRANSACTION_TX = 'ON_RECEIVE_TRANSACTION_TX' const ON_RECEIVE_TRANSACTION_TX = 'ON_RECEIVE_TRANSACTION_TX'
const ON_CHANGE_TRANSACTION_STATUS_DATA = 'ON_CHANGE_TRANSACTION_STATUS_DATA' const ON_CHANGE_TRANSACTION_STATUS_DATA = 'ON_CHANGE_TRANSACTION_STATUS_DATA'
// const BlockchainSDK = BlockchainTool.init()
const BlockchainSDK = { DiscoverService: {} }
BlockchainSDK.DiscoverService.getTxStatus = async tx => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1)
}, 5000)
})
}
BlockchainSDK.DiscoverService.getDAppDataById = async id => {
return new Promise((resolve, reject) => {
resolve({
metadata: {
name: 'Newly added',
url: 'https://www.astroledger.org/#/onSale',
description: 'Funding space grants with blockchain star naming',
image: '/images/dapps/astroledger.svg',
category: 'EXCHANGES',
dateAdded: '2019-10-10',
categoryPosition: 2,
},
rate: 10002345,
})
})
}
export const hideAction = () => ({ export const hideAction = () => ({
type: HIDE, type: HIDE,
payload: null, payload: null,
@ -73,11 +47,13 @@ export const checkTransactionStatusAction = tx => {
default: default:
case 1: case 1:
transacationStatus.setPublished(true) transacationStatus.setPublished(true)
dapp = await BlockchainSDK.DiscoverService.getDAppDataById( const blockchain = await BlockchainSDK.getInstance()
dapp = await blockchain.DiscoverService.getDAppDataById(
transacationStatus.dappId, transacationStatus.dappId,
) )
dapp = Object.assign(dapp.metadata, { dapp = Object.assign(dapp.metadata, {
sntValue: parseInt(dapp.rate, 10), id: dapp.id,
sntValue: parseInt(dapp.effectiveBalance, 10),
}) })
dispatch(onAddNewDappAction(dapp)) dispatch(onAddNewDappAction(dapp))
break break

View File

@ -1,5 +1,6 @@
import voteInitialState from '../../common/data/vote' import voteInitialState from '../../common/data/vote'
import reducerUtil from '../../common/utils/reducer' import reducerUtil from '../../common/utils/reducer'
import BlockchainSDK from '../../common/blockchain'
const SHOW_UP_VOTE = 'SHOW_UP_VOTE' const SHOW_UP_VOTE = 'SHOW_UP_VOTE'
const SHOW_DOWN_VOTE = 'SHOW_DOWN_VOTE' const SHOW_DOWN_VOTE = 'SHOW_DOWN_VOTE'
@ -9,29 +10,6 @@ const SWITCH_TO_DOWNVOTE = 'SWITCH_TO_DOWNVOTE'
const ON_INPUT_SNT_VALUE = 'ON_INPUT_SNT_VALUE' const ON_INPUT_SNT_VALUE = 'ON_INPUT_SNT_VALUE'
const UPDATE_AFTER_VOTING_VALUES = 'UPDATE_AFTER_VOTING_VALUES' const UPDATE_AFTER_VOTING_VALUES = 'UPDATE_AFTER_VOTING_VALUES'
const BlockchainSDK = { DiscoverService: {} }
BlockchainSDK.DiscoverService.upVoteEffect = (id, amount) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(amount)
}, 1000)
})
}
BlockchainSDK.DiscoverService.upVote = (id, amount) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('0xfae78787fa79')
}, 1000)
})
}
BlockchainSDK.DiscoverService.downVote = (id, amount) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('0xfae78787fa79')
}, 1000)
})
}
export const showUpVoteAction = dapp => { export const showUpVoteAction = dapp => {
window.location.hash = 'vote' window.location.hash = 'vote'
return { return {
@ -85,7 +63,8 @@ export const fetchVoteRatingAction = (dapp, isUpvote, sntValue) => {
if (isUpvote === true && voteState.sntValue !== sntValue.toString()) return if (isUpvote === true && voteState.sntValue !== sntValue.toString()) return
if (sntValue === 0) return if (sntValue === 0) return
const rating = await BlockchainSDK.DiscoverService.upVoteEffect( const blockchain = await BlockchainSDK.getInstance()
const rating = await blockchain.DiscoverService.upVoteEffect(
dapp.id, dapp.id,
sntValue, sntValue,
) )
@ -97,7 +76,8 @@ export const fetchVoteRatingAction = (dapp, isUpvote, sntValue) => {
export const upVoteAction = (dapp, amount) => { export const upVoteAction = (dapp, amount) => {
return async dispatch => { return async dispatch => {
dispatch(closeVoteAction()) dispatch(closeVoteAction())
const tx = await BlockchainSDK.DiscoverService.upVote(dapp.id, amount) const blockchain = await BlockchainSDK.getInstance()
const tx = await blockchain.DiscoverService.upVote(dapp.id, amount)
console.log('upvote', tx) console.log('upvote', tx)
} }
} }

View File

@ -16,7 +16,7 @@ config({
}, },
contracts: { contracts: {
"MiniMeToken": { "deploy": false }, "MiniMeToken": { "deploy": false },
"MiniMeTokenFactory": { }, "MiniMeTokenFactory": {},
"SNT": { "SNT": {
"instanceOf": "MiniMeToken", "instanceOf": "MiniMeToken",
"args": [ "args": [
@ -30,9 +30,9 @@ config({
] ]
}, },
"Discover": { "Discover": {
args: [ "$SNT" ] args: ["$SNT"]
}, },
"TestBancorFormula": { } "TestBancorFormula": {}
} }
}, (_err, web3_accounts) => { }, (_err, web3_accounts) => {
accounts = web3_accounts accounts = web3_accounts
@ -57,10 +57,10 @@ contract("Discover", function () {
let metadata = "QmSmv5e5DYc2otwWcpUzuqmt389s3HHx651TbxDvKBFFue"; let metadata = "QmSmv5e5DYc2otwWcpUzuqmt389s3HHx651TbxDvKBFFue";
await SNT.methods.generateTokens(accounts[0], amount).send(); await SNT.methods.generateTokens(accounts[0], amount).send();
const encodedCall = Discover.methods.createDApp(id,amount,TestUtils.getBytes32FromIpfsHash(metadata)).encodeABI(); const encodedCall = Discover.methods.createDApp(id, amount, TestUtils.getBytes32FromIpfsHash(metadata)).encodeABI();
await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({from: accounts[0]}); await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({ from: accounts[0] });
let receipt = await Discover.methods.dapps(0).call(); let receipt = await Discover.methods.dapps(0).call();
let developer = accounts[0]; let developer = accounts[0];
assert.strictEqual(developer, receipt.developer); assert.strictEqual(developer, receipt.developer);
@ -76,13 +76,13 @@ contract("Discover", function () {
let max = await Discover.methods.max().call(); let max = await Discover.methods.max().call();
let decimals = await Discover.methods.decimals().call(); let decimals = await Discover.methods.decimals().call();
let rate = Math.round(decimals - (amount * decimals/max)); let rate = Math.round(decimals - (amount * decimals / max));
assert.strictEqual(rate, parseInt(receipt.rate, 10)); assert.strictEqual(rate, parseInt(receipt.rate, 10));
let available = amount * rate; let available = amount * rate;
assert.strictEqual(available, parseInt(receipt.available, 10)); assert.strictEqual(available, parseInt(receipt.available, 10));
let votes_minted = Math.round((available/decimals) ** (decimals/rate)); let votes_minted = Math.round((available / decimals) ** (decimals / rate));
assert.strictEqual(votes_minted, parseInt(receipt.votesMinted, 10)); assert.strictEqual(votes_minted, parseInt(receipt.votesMinted, 10));
assert.strictEqual(0, parseInt(receipt.votesCast, 10)); assert.strictEqual(0, parseInt(receipt.votesCast, 10));
@ -95,10 +95,10 @@ contract("Discover", function () {
let metadata = 'QmSmv5e5DYc2otwWcpUzuqmt389s3HHx651TbxDvKBFFue'; let metadata = 'QmSmv5e5DYc2otwWcpUzuqmt389s3HHx651TbxDvKBFFue';
await SNT.methods.generateTokens(accounts[0], amount).send(); await SNT.methods.generateTokens(accounts[0], amount).send();
const encodedCall = Discover.methods.createDApp(id,amount, TestUtils.getBytes32FromIpfsHash(metadata)).encodeABI(); const encodedCall = Discover.methods.createDApp(id, amount, TestUtils.getBytes32FromIpfsHash(metadata)).encodeABI();
try { try {
await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({from: accounts[0]}); await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({ from: accounts[0] });
assert.fail('should have reverted before'); assert.fail('should have reverted before');
} catch (error) { } catch (error) {
TestUtils.assertJump(error); TestUtils.assertJump(error);
@ -114,17 +114,17 @@ contract("Discover", function () {
await SNT.methods.generateTokens(accounts[0], amount).send(); await SNT.methods.generateTokens(accounts[0], amount).send();
const encodedCall = Discover.methods.createDApp(id,amount,TestUtils.getBytes32FromIpfsHash(metadata)).encodeABI(); const encodedCall = Discover.methods.createDApp(id, amount, TestUtils.getBytes32FromIpfsHash(metadata)).encodeABI();
try { try {
await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({from: accounts[0]}); await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({ from: accounts[0] });
assert.fail('should have reverted before'); assert.fail('should have reverted before');
} catch (error) { } catch (error) {
TestUtils.assertJump(error); TestUtils.assertJump(error);
} }
const encodedCall0 = Discover.methods.createDApp(id,amount0,TestUtils.getBytes32FromIpfsHash(metadata)).encodeABI(); const encodedCall0 = Discover.methods.createDApp(id, amount0, TestUtils.getBytes32FromIpfsHash(metadata)).encodeABI();
try { try {
await SNT.methods.approveAndCall(Discover.options.address, amount0, encodedCall0).send({from: accounts[0]}); await SNT.methods.approveAndCall(Discover.options.address, amount0, encodedCall0).send({ from: accounts[0] });
assert.fail('should have reverted before'); assert.fail('should have reverted before');
} catch (error) { } catch (error) {
TestUtils.assertJump(error); TestUtils.assertJump(error);
@ -134,7 +134,7 @@ contract("Discover", function () {
it("should update the metadata correctly", async function () { it("should update the metadata correctly", async function () {
let id = "0x7465737400000000000000000000000000000000000000000000000000000000"; let id = "0x7465737400000000000000000000000000000000000000000000000000000000";
let metadata = "QmSmv5e5DYc2otwWcpUzuqmt389s3HHx651TbxDvKBFFeu"; let metadata = "QmSmv5e5DYc2otwWcpUzuqmt389s3HHx651TbxDvKBFFeu";
await Discover.methods.setMetadata(id,TestUtils.getBytes32FromIpfsHash(metadata)).send({ from: accounts[0] }); await Discover.methods.setMetadata(id, TestUtils.getBytes32FromIpfsHash(metadata)).send({ from: accounts[0] });
let receipt = await Discover.methods.dapps(0).call(); let receipt = await Discover.methods.dapps(0).call();
assert.strictEqual(TestUtils.getBytes32FromIpfsHash(metadata), receipt.metadata); assert.strictEqual(TestUtils.getBytes32FromIpfsHash(metadata), receipt.metadata);
}) })
@ -144,7 +144,7 @@ contract("Discover", function () {
let metadata_actual = "QmSmv5e5DYc2otwWcpUzuqmt389s3HHx651TbxDvKBFFeu"; let metadata_actual = "QmSmv5e5DYc2otwWcpUzuqmt389s3HHx651TbxDvKBFFeu";
let metadata = "QmSmv5e5DYc2otwWcpUzuqmt389s3HHx651TbxDvKBDDeu"; let metadata = "QmSmv5e5DYc2otwWcpUzuqmt389s3HHx651TbxDvKBDDeu";
try { try {
await Discover.methods.setMetadata(id,TestUtils.getBytes32FromIpfsHash(metadata)).send({ from: accounts[1] }); await Discover.methods.setMetadata(id, TestUtils.getBytes32FromIpfsHash(metadata)).send({ from: accounts[1] });
assert.fail('should have reverted before'); assert.fail('should have reverted before');
} catch (error) { } catch (error) {
TestUtils.assertJump(error); TestUtils.assertJump(error);
@ -160,14 +160,14 @@ contract("Discover", function () {
let initial = await Discover.methods.dapps(0).call(); let initial = await Discover.methods.dapps(0).call();
let before = await SNT.methods.balanceOf(Discover.options.address).call(); let before = await SNT.methods.balanceOf(Discover.options.address).call();
// This is the special case where no downvotes have yet been cast // This is the special case where no downvotes have yet been cast
let up_effect = await Discover.methods.upvoteEffect(id,amount).call(); let up_effect = await Discover.methods.upvoteEffect(id, amount).call();
await SNT.methods.generateTokens(accounts[0], amount).send(); await SNT.methods.generateTokens(accounts[0], amount).send();
const encodedCall = Discover.methods.upvote(id,amount).encodeABI(); const encodedCall = Discover.methods.upvote(id, amount).encodeABI();
await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({from: accounts[0]}); await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({ from: accounts[0] });
let receipt = await Discover.methods.dapps(0).call(); let receipt = await Discover.methods.dapps(0).call();
let developer = accounts[0]; let developer = accounts[0];
assert.strictEqual(developer, receipt.developer); assert.strictEqual(developer, receipt.developer);
@ -184,13 +184,13 @@ contract("Discover", function () {
let max = await Discover.methods.max().call(); let max = await Discover.methods.max().call();
let decimals = await Discover.methods.decimals().call(); let decimals = await Discover.methods.decimals().call();
let rate = Math.round(decimals - (upvotedBalance * decimals/max)); let rate = Math.round(decimals - (upvotedBalance * decimals / max));
assert.strictEqual(rate, parseInt(receipt.rate, 10)); assert.strictEqual(rate, parseInt(receipt.rate, 10));
let available = upvotedBalance * rate; let available = upvotedBalance * rate;
assert.strictEqual(available, parseInt(receipt.available, 10)); assert.strictEqual(available, parseInt(receipt.available, 10));
let votes_minted = Math.round((available/decimals) ** (decimals/rate)); let votes_minted = Math.round((available / decimals) ** (decimals / rate));
assert.strictEqual(votes_minted, parseInt(receipt.votesMinted, 10)); assert.strictEqual(votes_minted, parseInt(receipt.votesMinted, 10));
// Only true for upvotes made when there are no downvotes // Only true for upvotes made when there are no downvotes
@ -206,9 +206,9 @@ contract("Discover", function () {
let amount = 0; let amount = 0;
await SNT.methods.generateTokens(accounts[0], 10000).send(); await SNT.methods.generateTokens(accounts[0], 10000).send();
const encodedCall = Discover.methods.upvote(id,amount).encodeABI(); const encodedCall = Discover.methods.upvote(id, amount).encodeABI();
try { try {
await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({from: accounts[0]}); await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({ from: accounts[0] });
assert.fail('should have reverted before'); assert.fail('should have reverted before');
} catch (error) { } catch (error) {
TestUtils.assertJump(error); TestUtils.assertJump(error);
@ -221,9 +221,9 @@ contract("Discover", function () {
let amount = parseInt(initial, 10); let amount = parseInt(initial, 10);
await SNT.methods.generateTokens(accounts[0], amount).send(); await SNT.methods.generateTokens(accounts[0], amount).send();
const encodedCall = Discover.methods.upvote(id,amount).encodeABI(); const encodedCall = Discover.methods.upvote(id, amount).encodeABI();
try { try {
await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({from: accounts[0]}); await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({ from: accounts[0] });
assert.fail('should have reverted before'); assert.fail('should have reverted before');
} catch (error) { } catch (error) {
TestUtils.assertJump(error); TestUtils.assertJump(error);
@ -240,9 +240,9 @@ contract("Discover", function () {
let bal_before = await SNT.methods.balanceOf(developer).call(); let bal_before = await SNT.methods.balanceOf(developer).call();
await SNT.methods.generateTokens(accounts[1], amount).send(); await SNT.methods.generateTokens(accounts[1], amount).send();
const encodedCall = Discover.methods.downvote(id,amount).encodeABI(); const encodedCall = Discover.methods.downvote(id, amount).encodeABI();
await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({from: accounts[1]}); await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({ from: accounts[1] });
let receipt = await Discover.methods.dapps(0).call(); let receipt = await Discover.methods.dapps(0).call();
assert.strictEqual(developer, receipt.developer); assert.strictEqual(developer, receipt.developer);
@ -278,9 +278,9 @@ contract("Discover", function () {
let bal_before = await SNT.methods.balanceOf(developer).call(); let bal_before = await SNT.methods.balanceOf(developer).call();
await SNT.methods.generateTokens(accounts[1], amount).send(); await SNT.methods.generateTokens(accounts[1], amount).send();
const encodedCall = Discover.methods.downvote(id,amount).encodeABI(); const encodedCall = Discover.methods.downvote(id, amount).encodeABI();
await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({from: accounts[1]}); await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({ from: accounts[1] });
let receipt = await Discover.methods.dapps(0).call(); let receipt = await Discover.methods.dapps(0).call();
assert.strictEqual(developer, receipt.developer); assert.strictEqual(developer, receipt.developer);
@ -313,17 +313,17 @@ contract("Discover", function () {
await SNT.methods.generateTokens(accounts[1], amount_above + amount_below).send(); await SNT.methods.generateTokens(accounts[1], amount_above + amount_below).send();
const encodedCall = Discover.methods.downvote(id,amount_above).encodeABI(); const encodedCall = Discover.methods.downvote(id, amount_above).encodeABI();
try { try {
await SNT.methods.approveAndCall(Discover.options.address, amount_above, encodedCall).send({from: accounts[1]}); await SNT.methods.approveAndCall(Discover.options.address, amount_above, encodedCall).send({ from: accounts[1] });
assert.fail('should have reverted before'); assert.fail('should have reverted before');
} catch (error) { } catch (error) {
TestUtils.assertJump(error); TestUtils.assertJump(error);
} }
const encodedCall1 = Discover.methods.downvote(id,amount_below).encodeABI(); const encodedCall1 = Discover.methods.downvote(id, amount_below).encodeABI();
try { try {
await SNT.methods.approveAndCall(Discover.options.address, amount_below, encodedCall1).send({from: accounts[1]}); await SNT.methods.approveAndCall(Discover.options.address, amount_below, encodedCall1).send({ from: accounts[1] });
assert.fail('should have reverted before'); assert.fail('should have reverted before');
} catch (error) { } catch (error) {
TestUtils.assertJump(error); TestUtils.assertJump(error);
@ -336,13 +336,13 @@ contract("Discover", function () {
let initial = await Discover.methods.dapps(0).call(); let initial = await Discover.methods.dapps(0).call();
let before = await SNT.methods.balanceOf(Discover.options.address).call(); let before = await SNT.methods.balanceOf(Discover.options.address).call();
let up_effect = await Discover.methods.upvoteEffect(id,amount).call(); let up_effect = await Discover.methods.upvoteEffect(id, amount).call();
await SNT.methods.generateTokens(accounts[0], amount).send(); await SNT.methods.generateTokens(accounts[0], amount).send();
const encodedCall = Discover.methods.upvote(id,amount).encodeABI(); const encodedCall = Discover.methods.upvote(id, amount).encodeABI();
await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({from: accounts[0]}); await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({ from: accounts[0] });
let receipt = await Discover.methods.dapps(0).call(); let receipt = await Discover.methods.dapps(0).call();
let developer = accounts[0]; let developer = accounts[0];
assert.strictEqual(developer, receipt.developer); assert.strictEqual(developer, receipt.developer);
@ -359,7 +359,7 @@ contract("Discover", function () {
let max = await Discover.methods.max().call(); let max = await Discover.methods.max().call();
let decimals = await Discover.methods.decimals().call(); let decimals = await Discover.methods.decimals().call();
let rate = Math.round(decimals - (upvotedBalance * decimals/max)); let rate = Math.round(decimals - (upvotedBalance * decimals / max));
assert.strictEqual(rate, parseInt(receipt.rate, 10)); assert.strictEqual(rate, parseInt(receipt.rate, 10));
let available = upvotedBalance * rate; let available = upvotedBalance * rate;
@ -371,7 +371,7 @@ contract("Discover", function () {
// and confirm that `upvote` still calculates the effective_balance correctly // and confirm that `upvote` still calculates the effective_balance correctly
let votes_cast = parseInt(receipt.votesCast, 10); let votes_cast = parseInt(receipt.votesCast, 10);
let e_balance = Math.round(upvotedBalance - ((votes_cast*rate/decimals)*(available/decimals/votes_minted))); let e_balance = Math.round(upvotedBalance - ((votes_cast * rate / decimals) * (available / decimals / votes_minted)));
assert.strictEqual(e_balance, parseInt(receipt.effectiveBalance, 10)); assert.strictEqual(e_balance, parseInt(receipt.effectiveBalance, 10));
// The effective_balance should also match upvoteEffect + initial.effectiveBalance // The effective_balance should also match upvoteEffect + initial.effectiveBalance
@ -384,22 +384,22 @@ contract("Discover", function () {
let amount = 10; let amount = 10;
let receipt = await Discover.methods.dapps(0).call(); let receipt = await Discover.methods.dapps(0).call();
let effect = await Discover.methods.upvoteEffect(id,amount).call(); let effect = await Discover.methods.upvoteEffect(id, amount).call();
// Mock receiving the SNT // Mock receiving the SNT
let mBalance = parseInt(receipt.balance, 10) + amount let mBalance = parseInt(receipt.balance, 10) + amount
let max = await Discover.methods.max().call(); let max = await Discover.methods.max().call();
let decimals = await Discover.methods.decimals().call(); let decimals = await Discover.methods.decimals().call();
let mRate = Math.round(decimals - (mBalance * decimals/max)); let mRate = Math.round(decimals - (mBalance * decimals / max));
let mAvailable = mBalance * mRate; let mAvailable = mBalance * mRate;
let mVMinted = Math.round((mAvailable/decimals) ** (decimals/mRate)); let mVMinted = Math.round((mAvailable / decimals) ** (decimals / mRate));
// Votes have been cast by this stage, so we need to check how many there are // Votes have been cast by this stage, so we need to check how many there are
// and confirm that `upvoteEffect` mocks the effect correctly // and confirm that `upvoteEffect` mocks the effect correctly
let votes_cast = parseInt(receipt.votesCast, 10); let votes_cast = parseInt(receipt.votesCast, 10);
let mEBalance = Math.round(mBalance - ((votes_cast*mRate/decimals)*(mAvailable/decimals/mVMinted))); let mEBalance = Math.round(mBalance - ((votes_cast * mRate / decimals) * (mAvailable / decimals / mVMinted)));
let effect_calc = mEBalance - receipt.effectiveBalance; let effect_calc = mEBalance - receipt.effectiveBalance;
// Confirm that what is returned is (mEBalance - d.effective_balance) // Confirm that what is returned is (mEBalance - d.effective_balance)
@ -411,7 +411,7 @@ contract("Discover", function () {
let initial = await Discover.methods.max().call(); let initial = await Discover.methods.max().call();
let amount = parseInt(initial, 10); let amount = parseInt(initial, 10);
try { try {
await Discover.methods.upvoteEffect(id,amount).call(); await Discover.methods.upvoteEffect(id, amount).call();
assert.fail('should have reverted before'); assert.fail('should have reverted before');
} catch (error) { } catch (error) {
TestUtils.assertJump(error); TestUtils.assertJump(error);
@ -425,7 +425,7 @@ contract("Discover", function () {
let initial = await Discover.methods.dapps(0).call(); let initial = await Discover.methods.dapps(0).call();
let before = await SNT.methods.balanceOf(Discover.options.address).call(); let before = await SNT.methods.balanceOf(Discover.options.address).call();
let before_dev = await SNT.methods.balanceOf(accounts[0]).call(); let before_dev = await SNT.methods.balanceOf(accounts[0]).call();
let receipt_obj = await Discover.methods.withdraw(id,amount).send({from: accounts[0]}); let receipt_obj = await Discover.methods.withdraw(id, amount).send({ from: accounts[0] });
let receipt = receipt_obj.events.Withdraw.returnValues; let receipt = receipt_obj.events.Withdraw.returnValues;
assert.strictEqual(id, receipt.id); assert.strictEqual(id, receipt.id);
@ -434,7 +434,7 @@ contract("Discover", function () {
let after = await SNT.methods.balanceOf(Discover.options.address).call(); let after = await SNT.methods.balanceOf(Discover.options.address).call();
let after_dev = await SNT.methods.balanceOf(accounts[0]).call(); let after_dev = await SNT.methods.balanceOf(accounts[0]).call();
let difference = parseInt(before, 10) - parseInt(after, 10); let difference = parseInt(before, 10) - parseInt(after, 10);
let difference_dev = parseInt(after_dev, 10) - parseInt(before_dev, 10); let difference_dev = parseInt(after_dev, 10) - parseInt(before_dev, 10);
assert.strictEqual(difference, amount) assert.strictEqual(difference, amount)
assert.strictEqual(difference_dev, amount) assert.strictEqual(difference_dev, amount)
@ -444,12 +444,12 @@ contract("Discover", function () {
let decimals = await Discover.methods.decimals().call(); let decimals = await Discover.methods.decimals().call();
let balance = parseInt(initial.balance, 10) - amount let balance = parseInt(initial.balance, 10) - amount
let rate = Math.round(decimals - (balance * decimals/max)); let rate = Math.round(decimals - (balance * decimals / max));
let available = Math.round(balance * rate); let available = Math.round(balance * rate);
let v_minted = Math.round((available/decimals) ** (decimals/rate)); let v_minted = Math.round((available / decimals) ** (decimals / rate));
let v_cast = parseInt(initial.votesCast, 10); let v_cast = parseInt(initial.votesCast, 10);
let e_balance = Math.ceil(balance - ((v_cast*rate/decimals)*(available/decimals/v_minted))); let e_balance = Math.ceil(balance - ((v_cast * rate / decimals) * (available / decimals / v_minted)));
let effective_balance = parseInt(receipt.newEffectiveBalance, 10); let effective_balance = parseInt(receipt.newEffectiveBalance, 10);
// We begin to run into precision limitations in the BancorFormula here. // We begin to run into precision limitations in the BancorFormula here.
@ -471,7 +471,7 @@ contract("Discover", function () {
let id = "0x7465737400000000000000000000000000000000000000000000000000000000"; let id = "0x7465737400000000000000000000000000000000000000000000000000000000";
let amount = 150000; let amount = 150000;
try { try {
await Discover.methods.withdraw(id,amount).send({from: accounts[0]}); await Discover.methods.withdraw(id, amount).send({ from: accounts[0] });
assert.fail('should have reverted before'); assert.fail('should have reverted before');
} catch (error) { } catch (error) {
TestUtils.assertJump(error); TestUtils.assertJump(error);
@ -483,7 +483,7 @@ contract("Discover", function () {
let receipt = await Discover.methods.dapps(0).call(); let receipt = await Discover.methods.dapps(0).call();
let amount = parseInt(receipt.available, 10) + 1; let amount = parseInt(receipt.available, 10) + 1;
try { try {
await Discover.methods.withdraw(id,amount).send({from: accounts[0]}); await Discover.methods.withdraw(id, amount).send({ from: accounts[0] });
assert.fail('should have reverted before'); assert.fail('should have reverted before');
} catch (error) { } catch (error) {
TestUtils.assertJump(error); TestUtils.assertJump(error);
@ -494,7 +494,7 @@ contract("Discover", function () {
let id = "0x7465737400000000000000000000000000000000000000000000000000000000"; let id = "0x7465737400000000000000000000000000000000000000000000000000000000";
let amount = 1000; let amount = 1000;
try { try {
await Discover.methods.withdraw(id,amount).send({from: accounts[1]}); await Discover.methods.withdraw(id, amount).send({ from: accounts[1] });
} catch (error) { } catch (error) {
TestUtils.assertJump(error); TestUtils.assertJump(error);
} }
@ -510,9 +510,9 @@ contract("Discover", function () {
let bal_before = await SNT.methods.balanceOf(developer).call(); let bal_before = await SNT.methods.balanceOf(developer).call();
await SNT.methods.generateTokens(accounts[1], amount).send(); await SNT.methods.generateTokens(accounts[1], amount).send();
const encodedCall = Discover.methods.downvote(id,amount).encodeABI(); const encodedCall = Discover.methods.downvote(id, amount).encodeABI();
await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({from: accounts[1]}); await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({ from: accounts[1] });
let receipt = await Discover.methods.dapps(0).call(); let receipt = await Discover.methods.dapps(0).call();
assert.strictEqual(developer, receipt.developer); assert.strictEqual(developer, receipt.developer);
@ -544,13 +544,13 @@ contract("Discover", function () {
let initial = await Discover.methods.dapps(0).call(); let initial = await Discover.methods.dapps(0).call();
let before = await SNT.methods.balanceOf(Discover.options.address).call(); let before = await SNT.methods.balanceOf(Discover.options.address).call();
let up_effect = await Discover.methods.upvoteEffect(id,amount).call(); let up_effect = await Discover.methods.upvoteEffect(id, amount).call();
await SNT.methods.generateTokens(accounts[0], amount).send(); await SNT.methods.generateTokens(accounts[0], amount).send();
const encodedCall = Discover.methods.upvote(id,amount).encodeABI(); const encodedCall = Discover.methods.upvote(id, amount).encodeABI();
await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({from: accounts[0]}); await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({ from: accounts[0] });
let receipt = await Discover.methods.dapps(0).call(); let receipt = await Discover.methods.dapps(0).call();
let developer = accounts[0]; let developer = accounts[0];
assert.strictEqual(developer, receipt.developer); assert.strictEqual(developer, receipt.developer);
@ -567,7 +567,7 @@ contract("Discover", function () {
let max = await Discover.methods.max().call(); let max = await Discover.methods.max().call();
let decimals = await Discover.methods.decimals().call(); let decimals = await Discover.methods.decimals().call();
let rate = Math.round(decimals - (upvotedBalance * decimals/max)); let rate = Math.round(decimals - (upvotedBalance * decimals / max));
assert.strictEqual(rate, parseInt(receipt.rate, 10)); assert.strictEqual(rate, parseInt(receipt.rate, 10));
let available = upvotedBalance * rate; let available = upvotedBalance * rate;
@ -579,7 +579,7 @@ contract("Discover", function () {
// and confirm that `upvote` still calculates the effective_balance correctly // and confirm that `upvote` still calculates the effective_balance correctly
let votes_cast = parseInt(receipt.votesCast, 10); let votes_cast = parseInt(receipt.votesCast, 10);
let e_balance = Math.ceil(upvotedBalance - ((votes_cast*rate/decimals)*(available/decimals/votes_minted))); let e_balance = Math.ceil(upvotedBalance - ((votes_cast * rate / decimals) * (available / decimals / votes_minted)));
assert.strictEqual(e_balance, parseInt(receipt.effectiveBalance, 10)); assert.strictEqual(e_balance, parseInt(receipt.effectiveBalance, 10));
// The effective_balance should also match upvoteEffect + initial.effectiveBalance // The effective_balance should also match upvoteEffect + initial.effectiveBalance
@ -594,10 +594,10 @@ contract("Discover", function () {
let metadata = "QmSmv5e5DYc2otwWcpUzuqmt389s3HHx651TbxDvKBFFue"; let metadata = "QmSmv5e5DYc2otwWcpUzuqmt389s3HHx651TbxDvKBFFue";
await SNT.methods.generateTokens(accounts[0], amount).send(); await SNT.methods.generateTokens(accounts[0], amount).send();
const encodedCall = Discover.methods.createDApp(id,amount,TestUtils.getBytes32FromIpfsHash(metadata)).encodeABI(); const encodedCall = Discover.methods.createDApp(id, amount, TestUtils.getBytes32FromIpfsHash(metadata)).encodeABI();
await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({from: accounts[0]}); await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({ from: accounts[0] });
let receipt = await Discover.methods.dapps(1).call(); let receipt = await Discover.methods.dapps(1).call();
let developer = accounts[0]; let developer = accounts[0];
assert.strictEqual(developer, receipt.developer); assert.strictEqual(developer, receipt.developer);
@ -608,14 +608,14 @@ contract("Discover", function () {
let max = await Discover.methods.max().call(); let max = await Discover.methods.max().call();
let decimals = await Discover.methods.decimals().call(); let decimals = await Discover.methods.decimals().call();
let rate = Math.ceil(decimals - (amount * decimals/max)); let rate = Math.ceil(decimals - (amount * decimals / max));
assert.strictEqual(rate, parseInt(receipt.rate, 10)); assert.strictEqual(rate, parseInt(receipt.rate, 10));
let available = amount * rate; let available = amount * rate;
assert.strictEqual(available, parseInt(receipt.available, 10)); assert.strictEqual(available, parseInt(receipt.available, 10));
// It's checking that votesMinted doesn't overflow which we're really interested in here // It's checking that votesMinted doesn't overflow which we're really interested in here
let votes_minted = Math.round((available/decimals) ** (decimals/rate)); let votes_minted = Math.round((available / decimals) ** (decimals / rate));
let returned = parseInt(receipt.votesMinted, 10); let returned = parseInt(receipt.votesMinted, 10);
// Is going to be less than due to rounding inaccuracies at higher exponents // Is going to be less than due to rounding inaccuracies at higher exponents
@ -629,15 +629,15 @@ contract("Discover", function () {
let max = await Discover.methods.max().call(); let max = await Discover.methods.max().call();
// Choose a safeMax 1% higher than is currently set // Choose a safeMax 1% higher than is currently set
let safe = await Discover.methods.safeMax().call(); let safe = await Discover.methods.safeMax().call();
let percent = (safe/max * 100) + 1; let percent = (safe / max * 100) + 1;
let amount = parseInt(max, 10) * percent; let amount = parseInt(max, 10) * percent;
let metadata = "QmSmv5e5DYc2otwWcpUzuqmt389s3HHx651TbxDvKBFFue"; let metadata = "QmSmv5e5DYc2otwWcpUzuqmt389s3HHx651TbxDvKBFFue";
await SNT.methods.generateTokens(accounts[0], amount).send(); await SNT.methods.generateTokens(accounts[0], amount).send();
const encodedCall = Discover.methods.createDApp(id,amount,TestUtils.getBytes32FromIpfsHash(metadata)).encodeABI(); const encodedCall = Discover.methods.createDApp(id, amount, TestUtils.getBytes32FromIpfsHash(metadata)).encodeABI();
try { try {
await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({from: accounts[0]}); await SNT.methods.approveAndCall(Discover.options.address, amount, encodedCall).send({ from: accounts[0] });
} catch (error) { } catch (error) {
TestUtils.assertJump(error); TestUtils.assertJump(error);
} }