-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathutils.ts
345 lines (309 loc) · 10.2 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import BN = require('bn.js')
import { Observable } from 'rxjs'
import { first } from 'rxjs/operators'
import { IContractInfo, IProposalCreateOptions, Proposal } from '../src'
import { Arc } from '../src/arc'
import { DAO } from '../src/dao'
import { IProposalOutcome } from '../src/proposal'
import { Reputation } from '../src/reputation'
import { Address } from '../src/types'
const Web3 = require('web3')
const path = require('path')
export const graphqlHttpProvider: string = 'http://127.0.0.1:8000/subgraphs/name/daostack'
export const graphqlHttpMetaProvider: string = 'http://127.0.0.1:8000/subgraphs'
export const graphqlWsProvider: string = 'http://127.0.0.1:8001/subgraphs/name/daostack'
export const web3Provider: string = 'ws://127.0.0.1:8545'
export const ipfsProvider: string = 'http://127.0.0.1:5001/api/v0'
export const LATEST_ARC_VERSION = '0.0.1-rc.32'
export { BN }
export function padZeros(str: string, max = 36): string {
str = str.toString()
return str.length < max ? padZeros('0' + str, max) : str
}
const pks = [
// default accounts of ganache
'0x4f3edf983ac636a65a842ce7c78d9aa706d3b113bce9c46f30d7d21715b23b1d', // 0
'0x6cbed15c793ce57650b9877cf6fa156fbef513c4e6134f022a85b1ffdd59b2a1', // 1
'0x6370fd033278c143179d81c5526140625662b8daa446c22ee2d73db3707e620c', // 2
'0x646f1ce2fdad0e6deeeb5c7e8e5543bdde65e86029e2fd9fc169899c440a7913', // 3
'0xadd53f9a7e588d003326d1cbf9e4a43c061aadd9bc938c843a79e7b4fd2ad743', // 4
'0x395df67f0c2d2d9fe1ad08d1bc8b6627011959b79c53d7dd6a3536a33ab8a4fd', // 5
'0xb0057716d5917badaf911b193b12b910811c1497b5bada8d7711f758981c3773' // 9
]
export function fromWei(amount: BN): string {
return Web3.utils.fromWei(amount, 'ether')
}
export function toWei(amount: string | number): BN {
return new BN(Web3.utils.toWei(amount.toString(), 'ether'))
}
export interface ITestAddresses {
base: { [key: string]: Address },
dao: { [key: string]: Address },
test: {
organs: { [key: string]: Address },
Avatar: Address,
boostedProposalId: Address,
executedProposalId: Address,
queuedProposalId: Address,
preBoostedProposalId: Address,
[key: string]: Address | { [key: string]: Address }
}
}
export function getTestAddresses(arc: Arc, version: string = LATEST_ARC_VERSION): ITestAddresses {
// const contractInfos = arc.contractInfos
const migrationFile = path.resolve(`${require.resolve('@daostack/migration')}/../migration.json`)
const migration = require(migrationFile).private
let UGenericScheme: string = ''
try {
UGenericScheme = arc.getContractInfoByName('GenericScheme', version).address
} catch (err) {
if (err.message.match(/no contract/i)) {
// pass
} else {
throw err
}
}
const addresses = {
base: {
ContributionReward: arc.getContractInfoByName('ContributionReward', version).address,
GEN: arc.GENToken().address,
GenericScheme: arc.getContractInfoByName('GenericScheme', version).address,
SchemeRegistrar: arc.getContractInfoByName('SchemeRegistrar', version).address,
UGenericScheme
},
dao: migration.dao[version],
test: migration.test[version]
}
return addresses
}
export async function getOptions(web3: any) {
const block = await web3.eth.getBlock('latest')
return {
from: web3.eth.defaultAccount,
gas: block.gasLimit - 100000
}
}
export async function newArc(options: { [key: string]: any } = {}): Promise<Arc> {
const defaultOptions = {
graphqlHttpProvider,
graphqlWsProvider,
ipfsProvider,
web3Provider
}
const arc = new Arc(Object.assign(defaultOptions, options))
// get the contract addresses from the subgraph
await arc.fetchContractInfos()
for (const pk of pks) {
const account = arc.web3.eth.accounts.privateKeyToAccount(pk)
arc.web3.eth.accounts.wallet.add(account)
}
arc.web3.eth.defaultAccount = arc.web3.eth.accounts.wallet[0].address
return arc
}
/**
* Arc without a valid ethereum connection
* @return [description]
*/
export async function newArcWithoutEthereum(): Promise<Arc> {
const arc = new Arc({
graphqlHttpProvider,
graphqlWsProvider
})
return arc
}
/**
* Arc instance without a working graphql connection
* @return [description]
*/
export async function newArcWithoutGraphql(): Promise<Arc> {
const arc = new Arc({
ipfsProvider,
web3Provider
})
const normalArc = await newArc()
arc.setContractInfos(normalArc.contractInfos)
return arc
}
export async function getTestDAO(arc?: Arc, version: string = LATEST_ARC_VERSION) {
if (!arc) {
arc = await newArc()
}
const addresses = await getTestAddresses(arc, version)
if (!addresses.test.Avatar) {
const msg = `Expected to find ".test.avatar" in the migration file, found ${addresses} instead`
throw Error(msg)
}
return arc.dao(addresses.test.Avatar)
}
export async function createAProposal(
dao?: DAO,
options: any = {}
) {
if (!dao) {
dao = await getTestDAO()
}
options = {
beneficiary: '0xffcf8fdee72ac11b5c542428b35eef5769c409f0',
ethReward: toWei('300'),
externalTokenAddress: undefined,
externalTokenReward: toWei('0'),
nativeTokenReward: toWei('1'),
periodLength: 0,
periods: 1,
reputationReward: toWei('10'),
scheme: getTestAddresses(dao.context).base.ContributionReward,
...options
}
const response = await (dao as DAO).createProposal(options as IProposalCreateOptions).send()
const proposal = response.result as Proposal
// wait for the proposal to be indexed
let indexed = false
proposal.state().subscribe((next: any) => { if (next) { indexed = true } })
await waitUntilTrue(() => indexed)
return proposal
}
export async function mintSomeReputation(version: string = LATEST_ARC_VERSION) {
const arc = await newArc()
const addresses = getTestAddresses(arc, version)
const token = new Reputation(addresses.test.organs.DemoReputation, arc)
const accounts = arc.web3.eth.accounts.wallet
await token.mint(accounts[1].address, new BN('99')).send()
}
export function mineANewBlock() {
return mintSomeReputation()
}
export async function waitUntilTrue(test: () => Promise<boolean> | boolean) {
return new Promise((resolve) => {
(async function waitForIt(): Promise<void> {
if (await test()) { return resolve() }
setTimeout(waitForIt, 100)
})()
})
}
// Vote and vote and vote for proposal until it is accepted
export async function voteToPassProposal(proposal: Proposal) {
const arc = proposal.context
const accounts = arc.web3.eth.accounts.wallet
// make sure the proposal is indexed
await waitUntilTrue(async () => {
const state = await proposal.state({ fetchPolicy: 'network-only' }).pipe(first()).toPromise()
return !!state
})
for (let i = 0; i <= 3; i++) {
try {
arc.setAccount(accounts[i].address)
await proposal.vote(IProposalOutcome.Pass).send()
} catch (err) {
// TODO: this sometimes fails with uninformative `revert`, cannot find out why
if (err.message.match(/already executed/)) {
return
} else {
// ignore?
throw err
}
} finally {
arc.setAccount(accounts[0].address)
}
}
return
}
// export async function timeTravel(seconds: number, web3: any) {
// const jsonrpc = '2.0'
// // web3 = new Web3('http://localhost:8545')
// // web3.providers.HttpProvider.prototype.sendAsync = web3.providers.HttpProvider.prototype.send
// return new Promise((resolve, reject) => {
// web3.currentProvider.send({
// id: new Date().getTime(),
// jsonrpc,
// method: 'evm_increaseTime',
// // method: 'evm_mine',
// params: [seconds]
// }, (err1: Error) => {
// if (err1) { return reject(err1) }
// // resolve(res)
// web3.currentProvider.send({
// id: new Date().getTime(),
// jsonrpc,
// method: 'evm_mine'
// }, (err2: Error, res: any) => {
// return err2 ? reject(err2) : resolve(res)
// })
// })
// })
// }
const web3 = new Web3('http://127.0.0.1:8545')
export const advanceTime = (time: number) => {
return new Promise((resolve, reject) => {
web3.currentProvider.send({
jsonrpc: '2.0',
method: 'evm_increaseTime',
params: [time],
id: new Date().getTime()
}, (err: Error, result: any) => {
if (err) { return reject(err) }
return resolve(result)
})
})
}
export const advanceBlock = () => {
return new Promise((resolve, reject) => {
web3.currentProvider.send({
jsonrpc: '2.0',
method: 'evm_mine',
id: new Date().getTime()
}, (err: Error, result: any) => {
if (err) { return reject(err) }
const newBlockHash = web3.eth.getBlock('latest').hash
return resolve(newBlockHash)
})
})
}
export const takeSnapshot = () => {
return new Promise((resolve, reject) => {
web3.currentProvider.send({
jsonrpc: '2.0',
method: 'evm_snapshot',
id: new Date().getTime()
}, (err: Error, snapshotId: string) => {
if (err) { return reject(err) }
return resolve(snapshotId)
})
})
}
export const revertToSnapShot = (id: string) => {
return new Promise((resolve, reject) => {
web3.currentProvider.send({
id: new Date().getTime(),
jsonrpc: '2.0',
method: 'evm_revert',
params: [id]
}, (err: Error, result: any) => {
if (err) { return reject(err) }
return resolve(result)
})
})
}
export const advanceTimeAndBlock = async (time: number) => {
await advanceTime(time)
await advanceBlock()
return Promise.resolve(web3.eth.getBlock('latest'))
}
export async function firstResult(observable: Observable<any>) {
return observable.pipe(first()).toPromise()
}
export function getContractAddressesFromMigration(environment: 'private' | 'rinkeby' | 'mainnet'): IContractInfo[] {
const migration = require('@daostack/migration/migration.json')[environment]
const contracts: IContractInfo[] = []
for (const version of Object.keys(migration.base)) {
for (const name of Object.keys(migration.base[version])) {
contracts.push({
address: migration.base[version][name].toLowerCase(),
id: migration.base[version][name],
alias: migration.base[version][name], // fake the data for tests
name,
version
})
}
}
return contracts
}