This repository has been archived by the owner on Jun 23, 2022. It is now read-only.
/
client.js
281 lines (235 loc) · 7.61 KB
/
client.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
/* global ethereum:true */
/* global web3:true */
'use strict'
const createContractEvent = require('@drizzle-utils/contract-event-stream')
const createNewBlock = require('@drizzle-utils/new-block-stream')
const Web3 = require('web3')
const IpfsClient = require('ipfs-http-client')
const EthAvatarContract = require('./data/EthAvatar')
const Web3ProviderNotFoundError = require('./errors/Web3ProviderNotFoundError')
const ContractNotFoundError = require('./errors/ContractNotFoundError')
const InvalidAddressError = require('./errors/InvalidAddressError')
const Web3NotAllowedError = require('./errors/Web3NotAllowedError')
const DefaultAddressNotFoundError = require('./errors/DefaultAddressNotFoundError')
const GetAvatarError = require('./errors/GetAvatarError')
const SetAvatarError = require('./errors/SetAvatarError')
const RemoveAvatarError = require('./errors/RemoveAvatarError')
/**
* Client class for EthAvatar.
*
* @class
*/
class EthAvatar {
/**
* Construct the class and set up Web3, IPFS and Smart Contract connections.
*
* @param {object} [web3Conn] - Connection to Web3 provider (default is current Web3 provider).
* @param {object} [ipfsConn] - Connection to IPFS API (default is Infura API).
* @param {string} [contract] - Smart contract address (default is deployed address).
*
* @constructor
*/
constructor (web3Conn = null, ipfsConn = null, contract = null) {
this._initialized = this._initialize(web3Conn, ipfsConn, contract)
}
async _initialize (web3Conn, ipfsConn, contract) {
// Get Web3 connection
if (web3Conn === null) {
// Modern dapp browsers
if (typeof ethereum !== 'undefined') {
this.web3 = new Web3(ethereum)
// Legacy dapp browsers
} else if (typeof web3 !== 'undefined') {
this.web3 = new Web3(web3.currentProvider)
// Other browsers
} else {
throw new Web3ProviderNotFoundError('Default Web3 provider not found')
}
} else {
this.web3 = web3Conn
}
// Get IPFS connection
if (ipfsConn === null) {
this.ipfs = new IpfsClient('https://ipfs.infura.io:5001')
} else {
this.ipfs = ipfsConn
}
// Get smart contract connection
if (contract === null) {
const network = await this.web3.eth.net.getId()
try {
contract = EthAvatarContract.networks[network].address
} catch (error) {
throw new ContractNotFoundError('Contract not found on current network')
}
}
this.contract = new this.web3.eth.Contract(EthAvatarContract.abi, contract)
}
async _address (address = null) {
if (address) {
if (this.web3.utils.isAddress(address)) {
return address
} else {
try {
address = await this.web3.eth.ens.getAddress(address)
} catch (error) {
if (error.message.includes('ENS is not supported on network')) {
throw new InvalidAddressError('Provided address invalid and ENS not supported')
}
throw new InvalidAddressError('Provided address invalid and ENS domain not found')
}
return address
}
}
// Enable Web3 provider (EIP-1102)
if (typeof this.web3.currentProvider.enable !== 'undefined') {
try {
await this.web3.currentProvider.enable()
} catch (error) /* istanbul ignore next */ {
const err = new Web3NotAllowedError(error)
err.stack = error.stack
throw err
}
}
// Get Ethereum address
const accounts = await this.web3.eth.getAccounts()
if (typeof accounts[0] !== 'undefined') {
return accounts[0]
} else /* istanbul ignore next */ {
throw new DefaultAddressNotFoundError('Default Ethereum address not found')
}
}
/**
* Get avatar of Ethereum address.
*
* @param {string} [address] - Address or ENS domain to get avatar (default is current Ethereum address).
*
* @return {buffer} - Buffer data of avatar.
*
* @async
*/
async get (address = null) {
await this._initialized
// Get address
address = await this._address(address)
// Get avatar
try {
// Get avatar hash from contract
const hash = await this.contract.methods.getIPFSHash(address).call()
// Cancel if avatar is not set
if (hash === '') {
return
}
// Get avatar data from IPFS
let data
for await (const result of this.ipfs.get(hash)) {
let chunks = Buffer.from([])
for await (const chunk of result.content) {
chunks = Buffer.concat([chunks, chunk.slice()])
}
data = JSON.parse(chunks.toString())
break
}
// Get avatar image from IPFS
let image
for await (const result of this.ipfs.get(data.imageHash)) {
let chunks = Buffer.from([])
for await (const chunk of result.content) {
chunks = Buffer.concat([chunks, chunk.slice()])
}
image = chunks
break
}
// Return image
return image
} catch (error) /* istanbul ignore next */ {
const err = new GetAvatarError(error.message)
err.stack = error.stack
throw err
}
}
/**
* Set avatar of Ethereum address.
*
* @param {buffer} buffer - Buffer data of avatar.
*
* @return {void}
*
* @async
*/
async set (buffer) {
await this._initialized
// Get address
const address = await this._address()
// Set avatar
try {
// Set avatar image to IPFS
let imageHash
for await (const imageResult of this.ipfs.add(buffer)) {
imageHash = imageResult.cid.toString()
break
}
// Set avatar data to IPFS
const dataBuffer = Buffer.from(JSON.stringify({ imageHash: imageHash }))
let dataHash
for await (const dataResult of this.ipfs.add(dataBuffer)) {
dataHash = dataResult.cid.toString()
break
}
// Set avatar hash to contract
await this.contract.methods.setIPFSHash(dataHash).send({ from: address })
return
} catch (error) /* istanbul ignore next */ {
const err = new SetAvatarError(error.message)
err.stack = error.stack
throw err
}
}
/**
* Remove avatar of Ethereum address.
*
* @return {void}
*
* @async
*/
async remove () {
await this._initialized
// Get address
const address = await this._address()
// Remove avatar
try {
await this.contract.methods.setIPFSHash('').send({ from: address })
return
} catch (error) /* istanbul ignore next */ {
const err = new RemoveAvatarError(error.message)
err.stack = error.stack
throw err
}
}
/**
* Watch for avatar changes.
*
* @param {function} [callback] - Callback when event is received.
* @param {string} [address] - Address or ENS domain to watch (default is current Ethereum address).
*
* @return {void}
*/
watch (callback, address = null) {
this._initialized
.then(async () => {
// Get address
address = await this._address(address)
// Get contract event
const newBlock$ = createNewBlock({ web3: this.web3, pollingInterval: 200 }).observable
const contractEvent = createContractEvent({ abi: this.contract._jsonInterface, address: this.contract._address, web3: this.web3, newBlock$: newBlock$ })
// Watch for changes
contractEvent.subscribe(event => {
if (event.event === 'DidSetIPFSHash' && event.returnValues.hashAddress === address) {
const result = { hashAddress: event.returnValues.hashAddress, hash: event.returnValues.hash }
callback(result)
}
})
})
}
}
module.exports = EthAvatar