/
index.js
302 lines (270 loc) · 9.44 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
const ens = require('./ens')
const semver = require('semver')
const promiseTimeout = require('./utils/timeout-promise.js')
const ipfs = require('./providers/ipfs')
const http = require('./providers/http')
const GAS_FUZZ_FACTOR = 1.5
const GET_INFO_TIMEOUT = 10000 //ms
module.exports = (web3, options = {}) => {
const defaultOptions = {
ensRegistryAddress: null,
providers: {}
}
options = Object.assign(
defaultOptions,
options
)
// Set up providers
const defaultProviders = {
ipfs: ipfs(options.ipfs),
http: http(),
}
const providers = Object.assign(
defaultProviders,
options.providers
)
// Construct ENS options
const ensOptions = {
provider: web3.currentProvider,
registryAddress: options.ensRegistryAddress
}
const getProviderFromURI = (contentURI, path) => {
const [contentProvider, contentLocation] = contentURI.split(/:(.+)/)
if (!contentProvider || !contentLocation) {
throw new Error(`Invalid content URI (expected format was "<provider>:<identifier>")`)
}
if (!providers[contentProvider]) {
throw new Error(`The storage provider "${contentProvider}" is not supported`)
}
return { provider: providers[contentProvider], location: contentLocation }
}
const readFileFromApplication = (contentURI, path) => {
const { provider, location } = getProviderFromURI(contentURI, path)
return provider.getFile(location, path)
}
const readFileStreamFromApplication = (contentURI, path) => {
const { provider, location } = getProviderFromURI(contentURI, path)
return provider.getFileStream(location, path)
}
const formatVersion = version =>
version.split('.').map((part) => parseInt(part))
const getApplicationInfo = (contentURI) => {
const [provider, location] = contentURI.split(/:(.+)/)
let error;
if (!provider || !location) {
error = `contentURI: ${contentURI} is invalid.`
} else if (!providers[provider]) {
error = `Provider: ${provider} is not supported`
}
if (error) {
return Promise.resolve({
error,
contentURI
})
}
return Promise.all([
readFileFromApplication(contentURI, 'manifest.json'),
readFileFromApplication(contentURI, 'artifact.json')
])
.then((files) => files.map(JSON.parse))
.then(
([ manifest, module ]) => {
const [provider, location] = contentURI.split(':')
return Object.assign(
manifest,
module,
{ content: { provider, location } }
)
}
)
.catch(() => {
const [provider, location] = contentURI.split(':')
return {
content: { provider, location }
}
})
}
function returnVersion (web3, getInfoTimeout = GET_INFO_TIMEOUT) {
return (version) => {
const versionInfo = {
contractAddress: version.contractAddress,
version: version.semanticVersion.join('.')
}
return promiseTimeout(getApplicationInfo(web3.utils.hexToAscii(version.contentURI)), getInfoTimeout)
.then((info) => {
return Object.assign(info, versionInfo)
})
.catch((err) => versionInfo)
}
}
function getRepoId (appId) {
return appId.split('.').slice(1).join('.')
}
return {
validInitialVersions: ['0.0.1', '0.1.0', '1.0.0'],
getFile: readFileFromApplication,
getFileStream: readFileStreamFromApplication,
ensResolve: (name) => ens.resolve(name, ensOptions),
/**
* Get the APM repository registry address for `appId`.
*
* @param {string} appId
* @return {Promise} A promise that resolves to the APM address
*/
getRepoRegistryAddress (appId) {
const repoId = getRepoId(appId)
return this.ensResolve(repoId)
},
/**
* Get the APM repository registry contract for `appId`.
*
* @param {string} appId
* @return {Promise} A promise that resolves to the Web3 contract
*/
getRepoRegistry (appId) {
return this.getRepoRegistryAddress(appId)
.then(
(address) => new web3.eth.Contract(
require('@aragon/os/build/contracts/APMRegistry.json').abi,
address
)
)
},
/**
* Get the APM repository contract for `appId`.
*
* @param {string} appId
* @return {Promise} A promise that resolves to the Web3 contract
*/
getRepository (appId) {
return this.ensResolve(appId)
.then(
(address) => new web3.eth.Contract(
require('@aragon/os/build/contracts/Repo.json').abi,
address
)
)
},
getVersion (appId, version, getInfoTimeout) {
return this.getRepository(appId)
.then((repository) =>
repository.methods.getBySemanticVersion(version).call()
)
.then(returnVersion(web3, getInfoTimeout))
},
getVersionById (appId, versionId, getInfoTimeout) {
return this.getRepository(appId)
.then((repository) =>
repository.methods.getByVersionId(versionId).call()
)
.then(returnVersion(web3, getInfoTimeout))
},
getLatestVersion (appId, getInfoTimeout) {
return this.getRepository(appId)
.then((repository) =>
repository.methods.getLatest().call()
)
.then(returnVersion(web3, getInfoTimeout))
},
getLatestVersionContract (appId) {
return this.getRepository(appId)
.then((repository) =>
repository.methods.getLatest().call()
)
.then(({ contractAddress }) => contractAddress)
},
getLatestVersionForContract (appId, address, getInfoTimeout) {
return this.getRepository(appId)
.then((repository) =>
repository.methods.getLatestForContractAddress(address).call()
)
.then(returnVersion(web3, getInfoTimeout))
},
getAllVersions (appId) {
return this.getRepository(appId)
.then((repository) =>
repository.methods.getVersionsCount().call()
)
.then((versionCount) => {
const versions = []
for (let i = 1; i <= versionCount; i++) {
versions.push(this.getVersionById(appId, i))
}
return Promise.all(versions)
})
},
isValidBump (appId, fromVersion, toVersion) {
return this.getRepository(appId)
.then((repo) => (
repo.methods.isValidBump(formatVersion(fromVersion), formatVersion(toVersion)).call()
))
},
/**
* Publishes a new version (`version`) of `appId` using storage provider `provider`.
*
* If the destination repository does not exist, it falls back to creating a new
* repository with an initial version.
*
* Returns the raw transaction to sign.
*
* @param {string} manager The address that has access to manage this repository.
* @param {string} appId The ENS name for the application repository.
* @param {string} version A valid semantic version for this version.
* @param {string} provider The name of an APM storage provider.
* @param {string} directory The directory that contains files to publish.
* @param {string} contract The new contract address for this version.
* @return {Promise} A promise that resolves to a raw transaction
*/
async publishVersion (manager, appId, version, provider, directory, contract, from) {
if (!semver.valid(version)) {
throw new Error(`${version} is not a valid semantic version`)
}
if (!providers[provider]) {
throw new Error(`The storage provider "${provider}" is not supported`)
}
// Upload files to storage provider
const contentURI = Buffer.from(
await providers[provider].uploadFiles(directory)
).toString('hex')
// Resolve application repository
const repo = await this.getRepository(appId)
.catch(() => null)
// Default call creates a new repository and publishes the initial version
const repoRegistry = await this.getRepoRegistry(appId)
.catch(() => {
throw new Error(`Repository ${appId} does not exist and it's registry does not exist`)
})
let transactionDestination = repoRegistry.options.address
let call = repoRegistry.methods.newRepoWithVersion(
appId.split('.')[0],
manager,
formatVersion(version),
contract,
`0x${contentURI}`
)
// If the repository already exists, the call publishes a new version
if (repo !== null) {
transactionDestination = repo.options.address
call = repo.methods.newVersion(
formatVersion(version),
contract,
`0x${contentURI}`
)
}
try {
// Test that the call would actually succeed
await call.call({ from })
// Return transaction to sign
return {
to: transactionDestination,
data: call.encodeABI(),
gas: await call.estimateGas({ from }) * GAS_FUZZ_FACTOR,
gasPrice: web3.utils.toWei('10', 'gwei'),
nonce: await web3.eth.getTransactionCount(manager)
}
} catch (err) {
throw new Error(`Transaction would not succeed ("${err.message}")`)
}
}
}
}