-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathindex.js
1358 lines (1176 loc) · 44.4 KB
/
index.js
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Externals
import { ReplaySubject, Subject, BehaviorSubject, combineLatest, merge } from 'rxjs'
import {
map, startWith, scan, tap, publishReplay, switchMap, flatMap, filter, first,
debounceTime, skipWhile
} from 'rxjs/operators'
import uuidv4 from 'uuid/v4'
import Web3 from 'web3'
import { isAddress, toBN } from 'web3-utils'
import dotprop from 'dot-prop'
import * as radspec from 'radspec'
// APM
import { keccak256 } from 'js-sha3'
import { hash as namehash } from 'eth-ens-namehash'
import apm from '@aragon/apm'
// RPC
import Messenger from '@aragon/rpc-messenger'
import * as handlers from './rpc/handlers'
// Utilities
import { CALLSCRIPT_ID, encodeCallScript } from './evmscript'
import {
addressesEqual,
includesAddress,
makeAddressMapProxy,
makeProxy,
makeProxyFromABI,
getRecommendedGasLimit,
ANY_ENTITY
} from './utils'
import { getAragonOsInternalAppInfo, getKernelNamespace } from './core/aragonOS'
// Templates
import Templates from './templates'
// Cache
import Cache from './cache'
// Interfaces
import { getAbi } from './interfaces'
// Cache for proxy values
const proxyValuesCache = makeAddressMapProxy({})
// Cache for app info, usually fetched from apm
const appInfoCache = {}
// Try to get an injected web3 provider, return a public one otherwise.
export const detectProvider = () =>
typeof web3 !== 'undefined'
? web3.currentProvider // eslint-disable-line
: 'wss://rinkeby.eth.aragon.network/ws'
/**
* Set up an instance of the template factory that can be used independently
*
* @param {string} from
* The address of the account using the factory.
* @param {Object} options
* Template factory options.
* @param {Object} [options.apm]
* Options for apm.js (see https://github.com/aragon/apm.js)
* @param {string} [options.apm.ensRegistryAddress]
* ENS registry for apm.js
* @param {Object} [options.apm.ipfs]
* IPFS provider config for apm.js
* @param {string} [options.apm.ipfs.gateway]
* IPFS gateway apm.js will use to fetch artifacts from
* @param {Function} [options.defaultGasPriceFn=function]
* A factory function to provide the default gas price for transactions.
* It can return a promise of number string or a number string. The function
* has access to a recommended gas limit which can be used for custom
* calculations. This function can also be used to get a good gas price
* estimation from a 3rd party resource.
* @param {string|Object} [options.provider=web3.currentProvider]
* The Web3 provider to use for blockchain communication. Defaults to `web3.currentProvider`
* if web3 is injected, otherwise will fallback to wss://rinkeby.eth.aragon.network/ws
* @return {Object} Template factory instance
*/
export const setupTemplates = (from, options = {}) => {
const defaultOptions = {
apm: {},
defaultGasPriceFn: () => { },
provider: detectProvider()
}
options = Object.assign(defaultOptions, options)
const web3 = new Web3(options.provider)
return Templates(from, {
web3,
apm: apm(web3, options.apm),
defaultGasPriceFn: options.defaultGasPriceFn
})
}
/**
* An Aragon wrapper.
*
* @param {string} daoAddress
* The address of the DAO.
* @param {Object} options
* Wrapper options.
* @param {Object} [options.apm]
* Options for apm.js (see https://github.com/aragon/apm.js)
* @param {string} [options.apm.ensRegistryAddress]
* ENS registry for apm.js
* @param {Object} [options.apm.ipfs]
* IPFS provider config for apm.js
* @param {string} [options.apm.ipfs.gateway]
* IPFS gateway apm.js will use to fetch artifacts from
* @param {Function} [options.defaultGasPriceFn=function]
* A factory function to provide the default gas price for transactions.
* It can return a promise of number string or a number string. The function
* has access to a recommended gas limit which can be used for custom
* calculations. This function can also be used to get a good gas price
* estimation from a 3rd party resource.
* @param {string|Object} [options.provider=web3.currentProvider]
* The Web3 provider to use for blockchain communication. Defaults to `web3.currentProvider`
* if web3 is injected, otherwise will fallback to wss://rinkeby.eth.aragon.network/ws
*/
export default class Aragon {
constructor (daoAddress, options = {}) {
const defaultOptions = {
apm: {},
defaultGasPriceFn: () => { },
provider: detectProvider()
}
options = Object.assign(defaultOptions, options)
// Set up Web3
this.web3 = new Web3(options.provider)
// Set up APM
this.apm = apm(this.web3, options.apm)
// Set up the kernel proxy
this.kernelProxy = makeProxy(daoAddress, 'Kernel', this.web3)
// Set up cache
this.cache = new Cache(daoAddress)
this.defaultGasPriceFn = options.defaultGasPriceFn
}
/**
* Initialise the wrapper.
*
* @param {Object} [options] Options
* @param {Object} [options.accounts] `initAccount()` options (see below)
* @param {Object} [options.acl] `initACL()` options (see below)
* @return {Promise<void>}
* @throws {Error} Will throw an error if the `daoAddress` is detected to not be a Kernel instance
*/
async init (options = {}) {
let aclAddress
try {
// Check if address is kernel
// web3 throws if it's an empty address ('0x')
aclAddress = await this.kernelProxy.call('acl')
} catch (_) {
throw Error(`Provided daoAddress is not a DAO`)
}
await this.cache.init()
await this.kernelProxy.updateInitializationBlock()
await this.initAccounts(options.accounts)
await this.initAcl(Object.assign({ aclAddress }, options.acl))
this.initApps()
this.initForwarders()
this.initNetwork()
this.initNotifications()
this.transactions = new Subject()
}
/**
* Initialise the accounts observable.
*
* @param {Object} [options] Options
* @param {boolean} [options.fetchFromWeb3] Whether or not accounts should also be fetched from
* the provided Web3 instance
* @param {Array<string>} [options.providedAccounts] Array of accounts that the user controls
* @return {Promise<void>}
*/
async initAccounts ({ fetchFromWeb3, providedAccounts = [] } = {}) {
this.accounts = new ReplaySubject(1)
const accounts = fetchFromWeb3
? providedAccounts.concat(await this.web3.eth.getAccounts())
: providedAccounts
this.setAccounts(accounts)
}
/**
* Initialise the ACL (Access Control List).
*
* @return {Promise<void>}
*/
async initAcl ({ aclAddress } = {}) {
if (!aclAddress) {
aclAddress = await this.kernelProxy.call('acl')
}
// Set up ACL proxy
this.aclProxy = makeProxy(aclAddress, 'ACL', this.web3, this.kernelProxy.initializationBlock)
const SET_PERMISSION_EVENT = 'SetPermission'
const CHANGE_PERMISSION_MANAGER_EVENT = 'ChangePermissionManager'
const aclObservables = [
SET_PERMISSION_EVENT,
CHANGE_PERMISSION_MANAGER_EVENT
].map(event =>
this.aclProxy.events(event)
)
// Set up permissions observable
// Permissions Object:
// app -> role -> { manager, allowedEntities -> [ entities with permission ] }
this.permissions = merge(...aclObservables).pipe(
// Keep track of all the types of events that have been processed
scan(([permissions, eventSet], event) => {
const eventData = event.returnValues
// NOTE: dotprop.get() doesn't work through proxies, so we manually access permissions
const appPermissions = permissions[eventData.app] || {}
if (event.event === SET_PERMISSION_EVENT) {
const key = `${eventData.role}.allowedEntities`
// Converts to and from a set to avoid duplicated entities
const permissionsForRole = new Set(dotprop.get(appPermissions, key, []))
if (eventData.allowed) {
permissionsForRole.add(eventData.entity)
} else {
permissionsForRole.delete(eventData.entity)
}
dotprop.set(appPermissions, key, Array.from(permissionsForRole))
}
if (event.event === CHANGE_PERMISSION_MANAGER_EVENT) {
dotprop.set(appPermissions, `${eventData.role}.manager`, eventData.manager)
}
permissions[eventData.app] = appPermissions
return [permissions, eventSet.add(event.event)]
}, [makeAddressMapProxy({}), new Set()]),
// Skip until we have received events from all event subscriptions
// Note that this is safe as the ACL will always have to emit both
// ChangePermissionManager and SetPermission events every time a
// permission is created
skipWhile(([permissions, eventSet]) => eventSet.size < aclObservables.length),
map(([permissions]) => permissions),
// Throttle so it only continues after 30ms without new values
// Avoids DDOSing subscribers as during initialization there may be
// hundreds of events processed in a short timespan
debounceTime(30),
publishReplay(1)
)
this.permissions.connect()
}
/**
* Get proxy metadata (`appId`, address of the kernel, ...).
*
* @param {string} proxyAddress The address of the proxy to get metadata from
* @return {Promise<Object>}
*/
async getProxyValues (proxyAddress) {
// This function caches information about the AppProxy, as it is called for
// all the apps everytime a permission changes and this data won't change
// once it's fetched
const cachedValue = proxyValuesCache[proxyAddress]
if (cachedValue && cachedValue.kernelAddress && cachedValue.appId && cachedValue.codeAddress) {
return cachedValue
}
let proxyValues
if (this.isKernelAddress(proxyAddress)) {
const kernelProxy = makeProxy(proxyAddress, 'ERCProxy', this.web3, this.kernelProxy.initializationBlock)
proxyValues = await Promise.all([
// Use Kernel ABI
this.kernelProxy.call('KERNEL_APP_ID').catch(() => null),
// Use ERC897 proxy ABI
// Note that this won't work on old Aragon Core 0.5 Kernels,
// as they had not implemented ERC897 yet
kernelProxy
.call('implementation')
.catch(() => null)
]).then((values) => ({
proxyAddress,
appId: values[0],
codeAddress: values[1]
}))
} else {
const appProxy = makeProxy(proxyAddress, 'AppProxy', this.web3, this.kernelProxy.initializationBlock)
const appProxyForwarder = makeProxy(proxyAddress, 'Forwarder', this.web3, this.kernelProxy.initializationBlock)
proxyValues = await Promise.all([
appProxy.call('kernel').catch(() => null),
appProxy.call('appId').catch(() => null),
appProxy.call('implementation').catch(() => null),
appProxyForwarder.call('isForwarder').catch(() => false)
]).then((values) => ({
proxyAddress,
kernelAddress: values[0],
appId: values[1],
codeAddress: values[2],
isForwarder: values[3]
}))
}
proxyValuesCache[proxyAddress] = proxyValues
return proxyValues
}
/**
* Check if an object is an app.
*
* @param {Object} app
* @return {boolean}
*/
isApp (app) {
return app.kernelAddress && this.isKernelAddress(app.kernelAddress)
}
/**
* Check if an address is this DAO's kernel.
*
* @param {string} address
* @return {boolean}
*/
isKernelAddress (address) {
return addressesEqual(address, this.kernelProxy.address)
}
/**
* Initialize apps observable.
*
* @return {void}
*/
initApps () {
// TODO: Refactor this a bit because it's pretty much an eye sore
this.identifiers = new Subject()
this.appsWithoutIdentifiers = this.permissions.pipe(
map(Object.keys),
// Add Kernel as the first "app"
map((addresses) => {
const appsWithoutKernel = addresses.filter((address) => !this.isKernelAddress(address))
return [this.kernelProxy.address].concat(appsWithoutKernel)
}),
// Get proxy values
switchMap(
(appAddresses) => Promise.all(
appAddresses.map((app) => this.getProxyValues(app))
)
),
map(appMetadata => appMetadata.filter(
(app) => this.isApp(app) || this.isKernelAddress(app.proxyAddress)
)),
// Get artifact info
flatMap(
(apps) => Promise.all(
apps.map(async (app) => {
if (!app.appId || !app.codeAddress) {
return app
}
const cacheKey = `${app.appId}.${app.codeAddress}`
const cachedAppInfo = dotprop.get(appInfoCache, cacheKey)
const appInfo =
cachedAppInfo ||
getAragonOsInternalAppInfo(app.appId) ||
(await this.apm
.getLatestVersionForContract(app.appId, app.codeAddress)
// Just silence any errors
.catch(() => { }))
if (!cachedAppInfo && appInfo) {
dotprop.set(appInfoCache, cacheKey, appInfo)
}
return Object.assign(app, appInfo)
})
)
),
// Replaying the last emitted value is necessary for this.apps' combineLatest to not rerun
// this entire operator chain on identifier emits (doing so causes unnecessary apm fetches)
publishReplay(1)
)
this.appsWithoutIdentifiers.connect()
this.apps = combineLatest(
this.appsWithoutIdentifiers,
this.identifiers.pipe(
scan(
(identifiers, { address, identifier }) =>
Object.assign(identifiers, { [address]: identifier }),
{}),
startWith({})
),
function attachIdentifiers (apps, identifiers) {
return apps.map(
(app) => {
if (identifiers[app.proxyAddress]) {
return Object.assign(app, { identifier: identifiers[app.proxyAddress] })
}
return app
}
)
}
).pipe(
publishReplay(1)
)
this.apps.connect()
}
/**
* Set the identifier of an app.
*
* @param {string} address The proxy address of the app
* @param {string} identifier The identifier of the app
* @return {void}
*/
setAppIdentifier (address, identifier) {
this.identifiers.next({
address,
identifier
})
}
/**
* Initialise forwarder observable.
*
* @return {void}
*/
initForwarders () {
this.forwarders = this.apps.pipe(
map(
(apps) => apps.filter((app) => app.isForwarder)
),
publishReplay(1)
)
this.forwarders.connect()
}
/**
* Initialise the network observable.
*
* @return {Promise<void>}
*/
async initNetwork () {
this.network = new ReplaySubject(1)
this.network.next({
id: await this.web3.eth.net.getId(),
type: await this.web3.eth.net.getNetworkType()
})
}
/**
* Initialise the notifications observable.
*
* @return {void}
*/
initNotifications () {
// If the cached notifications doesn't exist or isn't an array, set it to an empty one
let cached = this.cache.get('notifications')
if (!Array.isArray(cached)) {
cached = []
} else {
// Set up acknowledge for unread notifications
cached.forEach(notification => {
if (notification && !notification.read) {
notification.acknowledge = () => this.acknowledgeNotification(notification.id)
}
})
}
this.notifications = new BehaviorSubject(cached).pipe(
scan((notifications, { modifier, notification }) => modifier(notifications, notification)),
tap((notifications) => this.cache.set('notifications', notifications)),
publishReplay(1)
)
this.notifications.connect()
}
/**
* Send a notification.
*
* @param {string} app The address of the app sending the notification
* @param {string} title The notification title
* @param {string} body The notification body
* @param {object} [context={}] The application context to send back if the notification is clicked
* @param {Date} [date=new Date()] The date the notification was sent
* @return {void}
*/
sendNotification (app, title, body, context = {}, date = new Date()) {
const id = uuidv4()
const notification = {
app,
body,
context,
date,
id,
title,
read: false
}
this.notifications.next({
modifier: (notifications, notification) => {
// Find the first notification that's not before this new one
// and insert ahead of it if it exists
const newNotificationIndex = notifications.findIndex(
notification => ((new Date(notification.date)).getTime() >= date.getTime())
)
return newNotificationIndex === -1
? [...notifications, notification]
: [
...notifications.slice(0, newNotificationIndex),
notification,
...notifications.slice(newNotificationIndex)
]
},
notification: {
...notification,
acknowledge: () => this.acknowledgeNotification(id)
}
})
}
/**
* Acknowledge a notification.
*
* @param {string} id The notification's id
* @return {void}
*/
acknowledgeNotification (id) {
this.notifications.next({
modifier: (notifications) => {
const notificationIndex = notifications.findIndex(notification => notification.id === id)
// Copy the old notifications and replace the old notification with a read version
const newNotifications = [...notifications]
newNotifications[notificationIndex] = {
...notifications[notificationIndex],
read: true,
acknowledge: () => { }
}
return newNotifications
}
})
}
/**
* Clears a notification.
*
* @param {string} id The notification's id
* @return {void}
*/
clearNotification (id) {
this.notifications.next({
modifier: (notifications) => {
return notifications.pipe(
filter(notification => notification.id !== id)
)
}
})
}
/**
* Clears all notifications.
*
* @return {void}
*/
clearNotifications () {
this.notifications.next({
modifier: (notifications) => {
return []
}
})
}
/**
* Run an app.
*
* As there may be race conditions with losing messages from cross-context environments,
* running an app is split up into two parts:
*
* 1. Set up any required state for the app. This step is allowed to be asynchronous.
* 2. Connect the app to a running context, by associating the context's message provider
* to the app. This step is synchronous.
*
* @param {string} proxyAddress
* The address of the app proxy.
* @return {Promise<function>}
*/
async runApp (proxyAddress) {
// Step 1: Set up required state for the app
// Only get the first result from the observable, so our running contexts don't get
// reinitialized if new apps appear
const apps = await this.apps.pipe(first()).toPromise()
const app = apps.find((app) => addressesEqual(app.proxyAddress, proxyAddress))
// TODO: handle undefined (no proxy found), otherwise when calling app.proxyAddress next, it will throw
const appProxy = makeProxyFromABI(app.proxyAddress, app.abi, this.web3)
await appProxy.updateInitializationBlock()
// Step 2: Associate app with running context
return (sandboxMessengerProvider) => {
// Set up messenger
const messenger = new Messenger(
sandboxMessengerProvider
)
// Wrap requests with the application proxy
// Note that we have to do this synchronously with the creation of the message provider,
// as we otherwise risk race conditions and may lose messages
const request$ = messenger.requests().pipe(
map(request => ({ request, proxy: appProxy, wrapper: this })),
// Use the same request$ result in each handler
// Turns request$ into a subject
publishReplay(1)
)
request$.connect()
// Register request handlers
const shutdown = handlers.combineRequestHandlers(
handlers.createRequestHandler(request$, 'cache', handlers.cache),
handlers.createRequestHandler(request$, 'events', handlers.events),
handlers.createRequestHandler(request$, 'intent', handlers.intent),
handlers.createRequestHandler(request$, 'call', handlers.call),
handlers.createRequestHandler(request$, 'network', handlers.network),
handlers.createRequestHandler(request$, 'notification', handlers.notifications),
handlers.createRequestHandler(request$, 'external_call', handlers.externalCall),
handlers.createRequestHandler(request$, 'external_events', handlers.externalEvents),
handlers.createRequestHandler(request$, 'identify', handlers.identifier),
handlers.createRequestHandler(request$, 'accounts', handlers.accounts),
handlers.createRequestHandler(request$, 'describe_script', handlers.describeScript),
handlers.createRequestHandler(request$, 'web3_eth', handlers.web3Eth)
).subscribe(
(response) => messenger.sendResponse(response.id, response.payload)
)
// App context helper function
function setContext (context) {
return messenger.send('context', [context])
}
return {
shutdown,
setContext
}
}
}
/**
* Set the available accounts for the current user.
*
* @param {Array<string>} accounts
* @return {void}
*/
setAccounts (accounts) {
this.accounts.next(accounts)
}
/**
* Get the available accounts for the current user.
*
* @return {Promise<Array<string>>} An array of addresses
*/
getAccounts () {
return this.accounts.pipe(first()).toPromise()
}
/**
* @param {Array<Object>} transactionPath An array of Ethereum transactions that describe each step in the path
* @return {Promise<string>} transaction hash
*/
performTransactionPath (transactionPath) {
return new Promise((resolve, reject) => {
this.transactions.next({
transaction: transactionPath[0],
path: transactionPath,
accept (transactionHash) {
resolve(transactionHash)
},
reject (err) {
reject(err || new Error('The transaction was not signed'))
}
})
})
}
/**
* Performs an action on the ACL using transaction pathing
*
* @param {string} method
* @param {Array<*>} params
* @return {Promise<string>} transaction hash
*/
async performACLIntent (method, params) {
const path = await this.getACLTransactionPath(method, params)
return this.performTransactionPath(path)
}
/**
* Looks for app with the provided proxyAddress and returns its app object if found
*
* @param {string} proxyAddress
* @return {Promise<Object>} The app object
*/
getApp (proxyAddress) {
return this.apps.pipe(
map(apps => apps.find(app => addressesEqual(app.proxyAddress, proxyAddress))),
first()
).toPromise()
}
/**
* Decodes an EVM callscript and returns the transaction path it describes.
*
* @param {string} script
* @return {Array<Object>} An array of Ethereum transactions that describe each step in the path
*/
decodeTransactionPath (script) {
// TODO: Support callscripts with multiple transactions in one (i.e. one ID, multiple destinations)
function decodePathSegment (script) {
// Remove script identifier
script = script.substr(10)
// Get address
const destination = `0x${script.substr(0, 40)}`
script = script.substr(40)
// Get data
const dataLength = parseInt(`0x${script.substr(0, 8)}`) * 2
script = script.substr(8)
const data = `0x${script.substr(0, dataLength)}`
script = script.substr(dataLength)
return {
to: destination,
data
}
}
let scriptId = script.substr(0, 10)
if (scriptId !== CALLSCRIPT_ID) {
throw new Error(`Unknown script ID ${scriptId}`)
}
let path = []
while (script.startsWith(CALLSCRIPT_ID)) {
const segment = decodePathSegment(script)
// Set script
script = segment.data
// Push segment
path.push(segment)
}
return path
}
/**
* Calculate the transaction path for a transaction to `destination`
* that invokes `methodName` with `params`.
*
* @param {string} destination
* @param {string} methodName
* @param {Array<*>} params
* @param {string} [finalForwarder] Address of the final forwarder that can perfom the action
* @return {Promise<Array<Object>>} An array of Ethereum transactions that describe each step in the path
*/
async getTransactionPath (destination, methodName, params, finalForwarder) {
const accounts = await this.getAccounts()
for (let account of accounts) {
const path = await this.calculateTransactionPath(
account,
destination,
methodName,
params,
finalForwarder
)
if (path.length > 0) {
return this.describeTransactionPath(path)
}
}
return []
}
/**
* Get the permission manager for an `app`'s and `role`.
*
* @param {string} appAddress
* @param {string} roleHash
* @return {Promise<string>} The permission manager
*/
async getPermissionManager (appAddress, roleHash) {
const permissions = await this.permissions.pipe(first()).toPromise()
const appPermissions = permissions[appAddress]
return dotprop.get(appPermissions, `${roleHash}.manager`)
}
/**
* Calculates transaction path for performing a method on the ACL
*
* @param {string} method
* @param {Array<*>} params
* @return {Promise<Array<Object>>} An array of Ethereum transactions that describe each step in the path
*/
async getACLTransactionPath (method, params) {
const aclAddr = this.aclProxy.address
const acl = await this.getApp(aclAddr)
const functionArtifact = acl.functions.find(
({ sig }) => sig.split('(')[0] === method
)
if (!functionArtifact) {
throw new Error(`Method ${method} not found on ACL artifact`)
}
if (functionArtifact.roles && functionArtifact.roles.length !== 0) {
// createPermission can be done with regular transaction pathing (it has a regular ACL role)
return this.getTransactionPath(aclAddr, method, params)
} else {
// All other ACL functions don't have a role, the manager needs to be provided to aid transaction pathing
// Inspect ABI to find the position of the 'app' and 'role' parameters needed to get the permission manager
const methodABI = acl.abi.find(
(item) => item.name === method && item.type === 'function'
)
if (!methodABI) {
throw new Error(`Method ${method} not found on ACL ABI`)
}
const inputNames = methodABI.inputs.map((input) => input.name)
const appIndex = inputNames.indexOf('_app')
const roleIndex = inputNames.indexOf('_role')
if (appIndex === -1 || roleIndex === -1) {
throw new Error(`Method ${method} doesn't take _app and _role as input. Permission manager cannot be found.`)
}
const manager = await this.getPermissionManager(params[appIndex], params[roleIndex])
return this.getTransactionPath(aclAddr, method, params, manager)
}
}
/**
* Use radspec to create a human-readable description for each transaction in the given `path`
*
* @param {Array<Object>} path
* @return {Promise<Array<Object>>} The given `path`, with descriptions included at each step
*/
describeTransactionPath (path) {
return Promise.all(path.map(async (step) => {
const app = await this.getApp(step.to)
// No app artifact
if (!app) return step
// Missing methods in artifact
if (!app.functions) return step
// Find the method
const methodId = step.data.substr(2, 8)
const method = app.functions.find(
(method) => keccak256(method.sig).substr(0, 8) === methodId
)
// Method does not exist in artifact
if (!method) return step
const expression = method.notice
// No expression
if (!expression) return step
let description
let annotatedDescription
try {
description = await radspec.evaluate(
expression,
{
abi: app.abi,
transaction: step
},
{ ethNode: this.web3.currentProvider }
)
} catch (err) { }
if (description) {
const processed = await this.postprocessRadspecDescription(description)
description = processed.description
annotatedDescription = processed.annotatedDescription
}
return Object.assign(step, {
description,
annotatedDescription,
name: app.name,
identifier: app.identifier
})
}))
}
/**
* Look for known addresses and roles in a radspec description and substitute them with a human string
*
* @param {string} description
* @return {Promise<Object>} description and annotated description
*/
async postprocessRadspecDescription (description) {
const addressRegexStr = '0x[a-fA-F0-9]{40}'
const addressRegex = new RegExp(`^${addressRegexStr}$`)
const bytes32RegexStr = '0x[a-f0-9]{64}'
const bytes32Regex = new RegExp(`^${bytes32RegexStr}$`)
const combinedRegex = new RegExp(`\\b(${addressRegexStr}|${bytes32RegexStr})\\b`)
const tokens = description
.split(combinedRegex)
.map(token => token.trim())
.filter(token => token)
if (tokens.length <= 1) {
return { description }
}
const apps = await this.apps.pipe(first()).toPromise()
const roles = apps
.map(({ roles }) => roles || [])
.reduce((acc, roles) => acc.concat(roles), []) // flatten
const annotateAddress = (input) => {
if (addressesEqual(input, ANY_ENTITY)) {
return [input, "'Any account'", { type: 'any-account', value: ANY_ENTITY }]
}
const app = apps.find(
({ proxyAddress }) => addressesEqual(proxyAddress, input)
)
if (app) {
const replacement = `${app.name}${app.identifier ? ` (${app.identifier})` : ''}`
return [input, `'${replacement}'`, { type: 'app', value: app }]
}
return [input, input, { type: 'address', value: input }]
}
const annotateBytes32 = (input) => {
const role = roles.find(({ bytes }) => bytes === input)
if (role && role.name) {
return [input, `'${role.name}'`, { type: 'role', value: role }]
}
const app = apps.find(
({ appName }) => appName && namehash(appName) === input
)
if (app) {
// return the entire app as it contains APM package details
return [input, `'${app.appName}'`, { type: 'apmPackage', value: app }]
}
const namespace = getKernelNamespace(input)
if (namespace) {
return [input, `'${namespace.name}'`, { type: 'kernelNamespace', value: namespace }]
}
return [input, input, { type: 'bytes32', value: input }]
}
const annotateText = (input) => {
return [input, input, { type: 'text', value: input }]
}
const annotatedTokens = tokens.map(token => {
if (addressRegex.test(token)) {