-
Notifications
You must be signed in to change notification settings - Fork 17
/
arc.ts
465 lines (426 loc) · 15.4 KB
/
arc.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
import BN = require('bn.js')
import gql from 'graphql-tag'
import { Observable, Observer, of, Subscription } from 'rxjs'
import { map } from 'rxjs/operators'
import { DAO, IDAOQueryOptions } from './dao'
import { GraphNodeObserver, IApolloQueryOptions } from './graphnode'
export { IApolloQueryOptions } from './graphnode'
import { Event, IEventQueryOptions } from './event'
import { Logger } from './logger'
import { Operation, sendTransaction, web3receipt } from './operation'
import { IProposalQueryOptions, Proposal } from './proposal'
import { ISchemeQueryOptions, Scheme } from './scheme'
import { ABI_DIR } from './settings'
import { ITagQueryOptions, Tag } from './tag'
import { Token } from './token'
import { Address, IPFSProvider, Web3Provider } from './types'
import { isAddress } from './utils'
const IPFSClient = require('ipfs-http-client')
const Web3 = require('web3')
/**
* The Arc class holds all configuration.
* Any useage of the library typically will start with instantiating a new Arc instance
* @return an instance of Arc
*/
export class Arc extends GraphNodeObserver {
public web3Provider: Web3Provider = ''
public web3ProviderRead: Web3Provider = ''
public ipfsProvider: IPFSProvider
public pendingOperations: Observable<Array<Operation<any>>> = of()
public ipfs: any
public web3: typeof Web3
public web3Read: typeof Web3 // if provided, arc will read all data from this provider
/**
* a mapping of contrct names to contract addresses
*/
public contractInfos: IContractInfo[]
public contracts: {[key: string]: any} = {} // a cache for the contracts
public contractsR: {[key: string]: any} = {} // a cache for teh "read-only" contracts
// accounts obseved by ethBalance
public blockHeaderSubscription: Subscription|undefined = undefined
public observedAccounts: { [address: string]: {
observable?: Observable<BN>
observer?: Observer<BN>
lastBalance?: string
subscriptionsCount: number
}
} = {}
constructor(options: {
/** Information about the contracts. Cf. [[setContractInfos]] and [[fetchContractInfos]] */
contractInfos?: IContractInfo[]
graphqlHttpProvider?: string
graphqlWsProvider?: string
ipfsProvider?: IPFSProvider
web3Provider?: string
web3ProviderRead?: string
/** this function will be called before a query is sent to the graphql provider */
graphqlPrefetchHook?: (query: any) => void
/** determines whether a query should subscribe to updates from the graphProvider. Default is true. */
graphqlSubscribeToQueries?: boolean
}) {
super({
graphqlHttpProvider: options.graphqlHttpProvider,
graphqlSubscribeToQueries: options.graphqlSubscribeToQueries,
graphqlWsProvider: options.graphqlWsProvider
})
this.ipfsProvider = options.ipfsProvider || ''
if (options.web3Provider) {
this.web3 = new Web3(options.web3Provider)
}
if (options.web3ProviderRead) {
this.web3Read = new Web3(options.web3ProviderRead)
} else {
this.web3Read = this.web3
}
this.contractInfos = options.contractInfos || []
if (!this.contractInfos) {
Logger.warn('No contract addresses given to the Arc.constructor: expect most write operations to fail!')
}
if (this.ipfsProvider) {
this.ipfs = IPFSClient(this.ipfsProvider)
}
// by default, we subscribe to queries
if (options.graphqlSubscribeToQueries === undefined) {
options.graphqlSubscribeToQueries = true
}
}
/**
* set the contract addresses
* @param contractInfos a list of IContractInfo objects
* @return
*/
public async setContractInfos(contractInfos: IContractInfo[]) {
// reset the cache
this.contracts = {}
this.contractsR = {}
this.contractInfos = contractInfos
}
/**
* fetch contractInfos from the subgraph
* @return a list of IContractInfo instances
*/
public async fetchContractInfos(apolloQueryOptions: IApolloQueryOptions = {}): Promise<IContractInfo[]> {
const query = gql`query AllContractInfos {
contractInfos (first: 1000) {
id
name
version
address
}
}`
// const result = await this.getObservableList(query, itemMap, apolloQueryOptions).pipe(first()).toPromise()
const response = await this.sendQuery(query, apolloQueryOptions)
const result = response.data.contractInfos as IContractInfo[]
this.setContractInfos(result)
return result
}
/**
* get a DAO instance from an address
* @param address address of the dao Avatar
* @return an instance of a DAO
*/
public dao(address: Address): DAO {
isAddress(address)
return new DAO(address, this)
}
/**
* return an observable of the list of DAOs
* @param options options to pass on to the query
* @return [description]
*/
public daos(options: IDAOQueryOptions = {}, apolloQueryOptions: IApolloQueryOptions = {}): Observable<DAO[]> {
return DAO.search(this, options, apolloQueryOptions)
}
public tags(options: ITagQueryOptions = {}, apolloQueryOptions: IApolloQueryOptions = {}): Observable<Tag[]> {
return Tag.search(this, options, apolloQueryOptions)
}
public scheme(id: string): Scheme {
return new Scheme(id, this)
}
public schemes(
options: ISchemeQueryOptions = {},
apolloQueryOptions: IApolloQueryOptions = {}
): Observable<Scheme[]> {
return Scheme.search(this, options, apolloQueryOptions)
}
public proposal(id: string): Proposal {
return new Proposal(id, this)
}
public proposals(
options: IProposalQueryOptions = {},
apolloQueryOptions: IApolloQueryOptions = {}
): Observable<Proposal[]> {
return Proposal.search(this, options, apolloQueryOptions)
}
public events(
options: IEventQueryOptions = {},
apolloQueryOptions: IApolloQueryOptions = {}
): Observable<Event[]> {
return Event.search(this, options, apolloQueryOptions)
}
public ethBalance(owner: Address): Observable<BN> {
if (!this.observedAccounts[owner]) {
this.observedAccounts[owner] = {
subscriptionsCount: 1
}
}
if (this.observedAccounts[owner].observable) {
this.observedAccounts[owner].subscriptionsCount += 1
return this.observedAccounts[owner].observable as Observable<BN>
}
const observable = Observable.create((observer: Observer<BN>) => {
this.observedAccounts[owner].observer = observer
// get the current balance and return it
this.web3Read.eth.getBalance(owner)
.then((currentBalance: string) => {
const accInfo = this.observedAccounts[owner];
(accInfo.observer as Observer<BN>).next(new BN(currentBalance))
accInfo.lastBalance = currentBalance
})
.catch((err: Error) => observer.error(err))
// set up the blockheadersubscription if it does not exist yet
if (!this.blockHeaderSubscription) {
const subscribeToBlockHeaders = () => {
this.blockHeaderSubscription = this.web3Read.eth.subscribe('newBlockHeaders', async (err: Error) => {
Object.keys(this.observedAccounts).forEach(async (addr) => {
const accInfo = this.observedAccounts[addr]
if (err) {
(accInfo.observer as Observer<BN>).error(err)
} else {
try {
const balance = await this.web3Read.eth.getBalance(addr)
if (balance !== accInfo.lastBalance) {
(accInfo.observer as Observer<BN>).next(new BN(balance))
accInfo.lastBalance = balance
}
} catch (err) {
observer.error(err)
}
}
})
})
}
try {
subscribeToBlockHeaders()
} catch (err) {
if (err.message.match(/connection not open/g)) {
// we need to re-establish the connection and then resubscribe
this.web3.setProvider(this.web3Provider)
subscribeToBlockHeaders()
}
throw err
}
}
// unsubscribe
return () => {
this.observedAccounts[owner].subscriptionsCount -= 1
if (this.observedAccounts[owner].subscriptionsCount <= 0) {
delete this.observedAccounts[owner]
}
if (Object.keys(this.observedAccounts).length === 0 && this.blockHeaderSubscription) {
this.blockHeaderSubscription.unsubscribe()
this.blockHeaderSubscription = undefined
}
}
})
this.observedAccounts[owner].observable = observable
return observable
.pipe(map((item: any) => new BN(item)))
}
/**
* return information about the contract
* @param address [description]
* @return an IContractInfo instance
*/
public getContractInfo(address: Address) {
isAddress(address)
for (const contractInfo of this.contractInfos) {
if (contractInfo.address.toLowerCase() === address.toLowerCase()) {
return contractInfo
}
}
if (!this.contractInfos) {
throw Error(`no contract info was found - did you call "arc.setContractInfos()"?`)
}
throw Error(`No contract with address ${address} is known`)
}
public getContractInfoByName(name: string, version: string) {
for (const contractInfo of this.contractInfos) {
if (contractInfo.name === name && contractInfo.version === version) {
return contractInfo
}
}
if (!this.contractInfos) {
throw Error(`no contract info was found - did you call "arc.setContractInfos(...)"?`)
}
throw Error(`No contract with name ${name} and version ${version} is known`)
}
public getABI(address?: Address, abiName?: string, version?: string) {
if (address && !abiName || !version) {
const contractInfo = this.getContractInfo(address as Address)
abiName = contractInfo.name
version = contractInfo.version
if (abiName === 'GEN') {
abiName = 'ERC20'
}
}
// TODO: workaround for https://github.com/daostack/subgraph/pull/336
if (abiName === 'UGenericScheme') {
const versionNumber = Number(version.split('rc.')[1])
if (versionNumber < 24) {
abiName = 'GenericScheme'
}
}
// //End of workaround
const abi = require(`${ABI_DIR}/${version}/${abiName}.json`)
return abi
}
/**
* return a web3 Contract instance.
* @param address address of the contract to look up in self.contractInfos
* @param [abiName] (optional) name of the ABI (i.e. 'Avatar' or 'SchemeRegistrar').
* @param [version] (optional) Arc version of contract (https://www.npmjs.com/package/@daostack/arc)
* @return a web3 contract instance
*/
public getContract(address: Address, abi?: any, mode?: 'readonly') {
// we use a contract "cache" because web3 contract instances add an event listener
const readonlyContract = (mode === 'readonly' && this.web3Read !== this.web3)
if (readonlyContract && this.contractsR[address]) {
return this.contractsR[address]
} else if (this.contracts[address]) {
return this.contracts[address]
} else {
if (!abi) {
abi = this.getABI(address)
}
let contract: any
if (readonlyContract) {
contract = new this.web3Read.eth.Contract(abi, address)
this.contractsR[address] = contract
} else {
contract = new this.web3.eth.Contract(abi, address)
this.contracts[address] = contract
}
return contract
}
}
/**
* get the GEN Token
* @return a Token instance
*/
public GENToken() {
if (this.contractInfos) {
for (const contractInfo of this.contractInfos) {
if (contractInfo.name === 'GEN') {
return new Token(contractInfo.address, this)
}
}
throw Error(`Cannot find address of GEN Token - did you call setContractInfos?`)
} else {
throw Error(`No contract addresses known - did you run arc.setContractInfos()?`)
}
}
public getAccount(): Observable<Address> {
// this complex logic is to get the correct account both from the Web3 as well as from the Metamaask provider
// This polls for changes. But polling is Evil!
// cf. https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md#ear-listening-for-selected-account-changes
return Observable.create((observer: any) => {
const interval = 1000 /// poll once a second
let account: any
let prevAccount: any
const web3 = this.web3
if (web3.eth.accounts[0]) {
observer.next(web3.eth.accounts[0].address)
prevAccount = web3.eth.accounts[0].address
} else if (web3.eth.defaultAccount ) {
observer.next(web3.eth.defaultAccount)
prevAccount = web3.eth.defaultAccount
}
const timeout = setInterval(() => {
web3.eth.getAccounts().then((accounts: any) => {
if (accounts) {
account = accounts[0]
} else if (web3.eth.accounts) {
account = web3.eth.accounts[0].address
}
if (prevAccount !== account && account) {
web3.eth.defaultAccount = account
observer.next(account)
prevAccount = account
}
})
}, interval)
return() => clearTimeout(timeout)
})
}
public setAccount(address: Address) {
this.web3.eth.defaultAccount = address
}
public approveForStaking(spender: Address, amount: BN) {
return this.GENToken().approveForStaking(spender, amount)
}
/**
* How much GEN spender may spend on behalve of the owner
* @param owner Address of the owner of the tokens
* @param spender Address of the spender
* @return
*/
public allowance(owner: Address, spender: Address): Observable<BN> {
return this.GENToken().allowance(owner, spender)
}
/**
* send an Ethereum transaction
* @param transaction [description]
* @param mapToObject [description]
* @param errorHandler [description]
* @return An observable of
*/
public sendTransaction<T>(
transaction: any,
mapToObject: (receipt: web3receipt) => T,
errorHandler?: (error: Error) => Promise<Error> | Error
): Operation<T> {
return sendTransaction(this, transaction, mapToObject, errorHandler)
}
/**
* save data of a proposal to IPFS, return the IPFS hash
* @param options an Object to save. This object must have title, url and desction defined
* @return a Promise that resolves in the IPFS Hash where the file is saved
*/
public async saveIPFSData(options: { title?: string, url?: string, description?: string, tags?: string[]}):
Promise<string> {
let ipfsDataToSave: object = {}
if (options.title || options.url || options.description || options.tags !== undefined) {
if (!this.ipfsProvider) {
throw Error(`No ipfsProvider set on Arc instance - cannot save data on IPFS`)
}
ipfsDataToSave = {
description: options.description,
tags: options.tags,
title: options.title,
url: options.url
}
}
Logger.debug('Saving data on IPFS...')
let descriptionHash: string = ''
try {
const ipfsResponse = await this.ipfs.add(Buffer.from(JSON.stringify(ipfsDataToSave)))
descriptionHash = ipfsResponse[0].path
// pin the file
await this.ipfs.pin.add(descriptionHash)
} catch (error) {
throw error
}
Logger.debug(`Data saved successfully as ${descriptionHash}`)
return descriptionHash
}
}
export interface IContractAddresses {
[key: string]: Address
}
export interface IContractInfo {
id: string
version: string
address: Address
name: string
}