Skip to content

39 operations #43

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jan 20, 2019
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/arc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export class Arc {
* @param address [description]
* @return [description]
*/
public getBalance(address: Address): Observable < number > {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did you remove spaces at some of these and added at others?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my linter is confused. There is not tslint rule that I can find that enforces this spacing (palantir/tslint#3092). I think the format should be spaceless, and corrected it

public getBalance(address: Address): Observable<number> {
const web3 = new Web3(this.web3WsProvider)
// observe balance on new blocks
// (note that we are basically doing expensive polling here)
Expand Down
55 changes: 51 additions & 4 deletions src/operation.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Observable } from 'rxjs'
import { Observable, Observer } from 'rxjs'

export enum TransactionState {
Sent,
Expand All @@ -11,17 +11,64 @@ export enum TransactionState {
export interface ITransactionUpdate<T> {
state: TransactionState
/**
* depth of the transaction in the blockchain.
* number of confirmations
*/
depth: number
transactionHash: string
receipt?: object
confirmations?: number
/**
* Parsed return value from the method call
* or contract address in the case of contract creation tx.
*/
result: T
result?: T
}

/**
* An operation is a stream of transaction updates
*/
export type Operation<T> = Observable<ITransactionUpdate<T>>

type web3receipt = object

export function sendTransaction<T>(transaction: any, map: (receipt: web3receipt) => T): Operation<T> {
const emitter = transaction.send()
const observable = Observable.create((observer: Observer<ITransactionUpdate<T>>) => {
let transactionHash: string
let result: any
emitter
.once('transactionHash', (hash: string) => {
transactionHash = hash
observer.next({
state: TransactionState.Sent,
transactionHash
})
})
.once('receipt', (receipt: any) => {
result = map(receipt)
observer.next({
confirmations: 0,
receipt,
result,
state: TransactionState.Mined,
transactionHash
})
})
.on('confirmation', (confNumber: number, receipt: any) => {
observer.next({
confirmations: confNumber,
receipt,
result,
state: TransactionState.Mined,
transactionHash
})
if (confNumber > 23) {
// the web3 observer will confirm up to 24 subscriptions, so we are done here
observer.complete()
}
})
.on('error', (error: Error) => {
observer.error(error)
})
})
return observable
}
41 changes: 23 additions & 18 deletions src/proposal.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import gql from 'graphql-tag'
import { Observable, of } from 'rxjs'
import { Observable, Observer, of } from 'rxjs'
import { map } from 'rxjs/operators'

import { Arc } from './arc'
import { DAO } from './dao'
import { Operation } from './operation'
import { ITransactionUpdate, Operation, sendTransaction, TransactionState } from './operation'
import { IRewardQueryOptions, IRewardState, Reward } from './reward'
import { IStake, IStakeQueryOptions, Stake } from './stake'
import { Address, Date, ICommonQueryOptions, IStateful } from './types'
import { getOptions, nullAddress } from './utils'
import { getWeb3Options, nullAddress } from './utils'
import { IVote, IVoteQueryOptions, Vote } from './vote'

export enum ProposalOutcome {
Expand Down Expand Up @@ -56,16 +56,20 @@ export interface IProposalState {

export class Proposal implements IStateful<IProposalState> {

// Create a new proposal
// TODO: we want to return an observer for the transaction here
public static async create(options: IProposalCreateOptions, context: Arc) {
/**
* Proposal.create() creates a new proposal
* @param options cf. IProposalCreateOptions
* @param context [description]
* @return an observable that streams the various states
*/
public static create(options: IProposalCreateOptions, context: Arc): Operation<Proposal> {

if (!options.dao) {
throw Error(`Proposal.create(options): options must include an address for "dao"`)
}
const web3 = context.web3

const opts = await getOptions(web3)
const opts = getWeb3Options(web3)
const addresses = context.contractAddresses
const ContributionReward = require('@daostack/arc/build/contracts/ContributionReward.json')
const contributionReward = new web3.eth.Contract(ContributionReward.abi, addresses.ContributionReward, opts)
Expand All @@ -86,18 +90,19 @@ export class Proposal implements IStateful<IProposalState> {
options.externalTokenAddress || nullAddress,
options.beneficiary
)
const proposalId = await propose.call()
const transaction = await propose.send()
return { transaction, proposalId }

return sendTransaction(propose, (receipt: any) => {
const proposalId = receipt.events.NewContributionProposal.returnValues._proposalId
return new Proposal(proposalId, context)
})
}
/**
* `state` is an observable of the proposal state
*/
public state: Observable<IProposalState> = of()
public state: Observable < IProposalState > = of()
public context: Arc

constructor(public id: string, context: Arc) {
constructor(public id: string, context: Arc) {
this.id = id
this.context = context

Expand Down Expand Up @@ -201,33 +206,33 @@ export class Proposal implements IStateful<IProposalState> {

// Note that although this is implemented as an observable, the value is actually static
// and will never change.
public dao(): Observable<DAO> {
public dao(): Observable < DAO > {
return this.state.pipe(
map((state) => {
return state.dao
})
)
}

public votes(options: IVoteQueryOptions = {}): Observable<IVote[]> {
public votes(options: IVoteQueryOptions = {}): Observable < IVote[] > {
options.proposal = this.id
return Vote.search(this.context, options)
}

public vote(outcome: ProposalOutcome): Operation<void> {
public vote(outcome: ProposalOutcome): Operation < void > {
throw new Error('not implemented')
}

public stakes(options: IStakeQueryOptions = {}): Observable<IStake[]> {
public stakes(options: IStakeQueryOptions = {}): Observable < IStake[] > {
options.proposal = this.id
return Stake.search(this.context, options)
}

public stake(outcome: ProposalOutcome, amount: number): Operation<void> {
public stake(outcome: ProposalOutcome, amount: number): Operation < void > {
throw new Error('not implemented')
}

public rewards(options: IRewardQueryOptions = {}): Observable<IRewardState[]> {
public rewards(options: IRewardQueryOptions = {}): Observable < IRewardState[] > {
options.proposal = this.id
return Reward.search(this.context, options)
}
Expand Down
9 changes: 8 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export function checkWebsocket(options: { url: string }) {

export const nullAddress = '0x0000000000000000000000000000000000000000'

export async function getOptions(web3: any) {
export async function getOptionsFromChain(web3: any) {
if (web3.eth.defaultAccount === null) {
throw Error('No default account specified: please set web3.eth.defaultAccount')
}
Expand All @@ -90,3 +90,10 @@ export async function getOptions(web3: any) {
gas: block.gasLimit - 100000
}
}

export function getWeb3Options(web3: any) {
return {
from: web3.eth.defaultAccount,
gas: 7900000
}
}
14 changes: 13 additions & 1 deletion test/client.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ApolloClient } from 'apollo-client'
import gql from 'graphql-tag'
import { Observable, Observer } from 'rxjs'
import { reduce, take } from 'rxjs/operators'
import { Arc } from '../src/arc'
import { createApolloClient } from '../src/utils'
import { graphqlHttpProvider, graphqlWsProvider, mintSomeReputation, waitUntilTrue } from './utils'
Expand Down Expand Up @@ -42,7 +43,7 @@ describe('apolloClient', () => {
})

// TODO: skipping this test until https://github.com/daostack/subgraph/issues/58 is resolved
it.skip('handles subscriptions', async () => {
it('handles subscriptions', async () => {
client = getClient()
const query = gql`
subscription {
Expand Down Expand Up @@ -73,6 +74,17 @@ describe('apolloClient', () => {
throw err
}
)
// TODO: we can do all this more elegantly using the following pattern
// but until subscriptions work reliably in graph-node, i cannot be bother to test this
// const p = observable
// .pipe(
// take(2),
// reduce((acc: object[], val: object) => {
// console.log(val)
// acc.push(val); return acc
// }, [])
// )
// const xx = await p.toPromise()

await mintSomeReputation()
await mintSomeReputation()
Expand Down
34 changes: 8 additions & 26 deletions test/dao.spec.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,17 @@
import { first, last, takeLast} from 'rxjs/operators'
import { first } from 'rxjs/operators'
import { Arc } from '../src/arc'
import { DAO } from '../src/dao'
import { getArc, getContractAddresses, getContractAddressesFromSubgraph,
getOptions, getWeb3, nullAddress } from './utils'
import { getArc, getTestDAO, getWeb3 } from './utils'

/**
* DAO test
*/
describe('DAO', () => {
let addresses: { [key: string]: string }
let arc: Arc
let web3: any
let accounts: any

async function _getSomeDAOAddress() {
addresses = getContractAddresses()
const result = await getContractAddressesFromSubgraph()
return result.daos[0].address
// return result.daos[0].address
}

beforeAll(async () => {
addresses = getContractAddresses()
arc = getArc()
web3 = await getWeb3()
accounts = web3.eth.accounts.wallet
Expand All @@ -35,9 +25,7 @@ describe('DAO', () => {
})

it('should be possible to get the token balance of the DAO', async () => {
// const address = addresses.Avatar
const address = await _getSomeDAOAddress()
const dao = new DAO(address, arc)
const dao = await getTestDAO()
const { token } = await dao.state.pipe(first()).toPromise()
const balance = await token.balanceOf(dao.address).pipe(first()).toPromise()
expect(balance).toEqual(0)
Expand All @@ -53,18 +41,14 @@ describe('DAO', () => {
const daoList = await daos.pipe(first()).toPromise()
expect(typeof daoList).toBe('object')
expect(daoList.length).toBeGreaterThan(0)
// expect(daoList[daoList.length - 2].address).toBe(addresses.Avatar.toLowerCase())
})

it('get the dao state', async () => {
// const dao = arc.dao(addresses.Avatar.toLowerCase())
const address = await _getSomeDAOAddress()
const dao = arc.dao(address)
const dao = await getTestDAO()
expect(dao).toBeInstanceOf(DAO)
const state = await dao.state.pipe(first()).toPromise()
const expected = {
// address: addresses.Avatar.toLowerCase(),
address,
address: dao.address,
memberCount: 6,
name: 'Genesis Test'
}
Expand Down Expand Up @@ -97,23 +81,21 @@ describe('DAO', () => {

it.skip('dao.members() should work', async () => {
// TODO: because we have not setup with proposals, we are only testing if the current state returns the emty list
const address = await _getSomeDAOAddress()
const dao = arc.dao(address)
// const dao = arc.dao(addresses.Avatar.toLowerCase())
const dao = await getTestDAO()
const members = await dao.members().pipe(first()).toPromise()
expect(typeof members).toEqual(typeof [])
expect(members.length).toBeGreaterThan(0)
const member = members[0]
})

it('dao.ethBalance() should work', async () => {
const dao = arc.dao(addresses.Avatar.toLowerCase())
const dao = await getTestDAO()
const previousBalance = await dao.ethBalance().pipe(first()).toPromise()
await web3.eth.sendTransaction({
from: web3.eth.defaultAccount,
gas: 4000000,
gasPrice: 100000000000,
to: addresses.Avatar.toLowerCase(),
to: dao.address,
value: web3.utils.toWei('1', 'ether')
})
const newBalance = await dao.ethBalance().pipe(first()).toPromise()
Expand Down
46 changes: 43 additions & 3 deletions test/proposal-create.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { reduce, take } from 'rxjs/operators'
import { Arc } from '../src/arc'
import { DAO } from '../src/dao'
import { ITransactionUpdate, TransactionState } from '../src/operation'
import { Proposal } from '../src/proposal'
import { getArc } from './utils'

describe('Create ContributionReward Proposal', () => {
Expand All @@ -26,8 +29,45 @@ describe('Create ContributionReward Proposal', () => {
periods: 5,
type: 'ConributionReward'
}
const result = await dao.createProposal(options)
expect(result.proposalId).toHaveLength(66)
expect(result.proposalId).toMatch(/^0x/)

// collect the first 4 results of the observable in a a listOfUpdates array
const listOfUpdates = await dao.createProposal(options)
.pipe(
take(5),
reduce((acc: Array<ITransactionUpdate<Proposal>> , val: ITransactionUpdate<Proposal>) => {
acc.push(val); return acc
}, [])
)
.toPromise()

// the first returned value is expected to be the "sent" (i.e. not mined yet)
expect(listOfUpdates[0]).toMatchObject({
state: TransactionState.Sent
})
expect(listOfUpdates[1]).toMatchObject({
confirmations: 0,
state: TransactionState.Mined
})
expect(listOfUpdates[1].result).toBeDefined()
expect(listOfUpdates[1].receipt).toBeDefined()
expect(listOfUpdates[1].transactionHash).toBeDefined()

const proposal = listOfUpdates[1].result
if (proposal) {
expect(proposal.id).toBeDefined()
}

expect(listOfUpdates[2]).toMatchObject({
confirmations: 1,
state: TransactionState.Mined
})
expect(listOfUpdates[3]).toMatchObject({
confirmations: 2,
receipt: listOfUpdates[1].receipt,
// result: listOfUpdates[1].result,
state: TransactionState.Mined,
transactionHash: listOfUpdates[1].transactionHash
})

})
})
Loading