forked from factoria-org/f0js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
326 lines (322 loc) · 10.1 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
const abi = require('./abi.js')
const ipfsh = require('ipfsh')
const axios = require('axios')
const traverse = require('traverse')
const Invitelist = require('invitelist')
class F0 {
async init (options) {
this.abi = abi;
this._invites = {}
this.web3 = options.web3;
this.address = options.contract;
this.currency = options.currency ? options.currency : "usd"
// account
if (options.key) {
this.key = options.key
this.wallet = this.web3.eth.accounts.privateKeyToAccount("0x" + options.key)
this.account = this.wallet.address
} else {
this.key = null
this.wallet = null
let _res = await this.web3.eth.getAccounts()
this.account = _res[0];
}
// collection
this.collection = new this.web3.eth.Contract(this.abi, this.address);
// api
let methods = this.abi.filter((item) => { return item.type === 'function' })
this.api = {}
if (this.key) {
// node.js
for(let method of methods) {
this.api[method.name] = (...args) => {
return {
send: async (param) => {
let action = this.collection.methods[method.name](...args)
let data = action.encodeABI()
let o = {
from: (param && param.from ? param.from : this.account),
to: this.address,
data: data,
}
if (param && param.value) o.value = param.value
let estimate = await action.estimateGas(o)
o.gas = estimate
const signedTx = await this.wallet.signTransaction(o)
let tx = await this.web3.eth.sendSignedTransaction(signedTx.rawTransaction);
return tx
},
call: (param) => {
return this.collection.methods[method.name](...args).call(param)
},
estimate: async (param) => {
let action = this.collection.methods[method.name](...args)
let data = action.encodeABI()
let o = {
from: (param && param.from ? param.from : this.account),
to: this.address,
data: data,
}
if (param && param.value) o.value = param.value
let estimate = await action.estimateGas(o)
let e = await this.estimate(estimate)
e.gas = estimate
return e
}
}
}
}
} else {
// browser
for(let method of methods) {
this.api[method.name] = (...args) => {
return {
send: async (param) => {
let o = {
from: (param && param.from ? param.from : this.account),
}
if (param && param.value) o.value = param.value
let r = await this.collection.methods[method.name](...args).send(o)
return r
},
call: async (param) => {
let o = {
from: (param && param.from ? param.from : this.account),
}
if (param && param.value) o.value = param.value
let r = await this.collection.methods[method.name](...args).call(o)
return r
},
estimate: async (param) => {
let o = {
from: (param && param.from ? param.from : this.account),
}
if (param && param.value) o.value = param.value
let r = await this.collection.methods[method.name](...args).estimateGas(o)
let e = await this.estimate(r)
e.gas = estimate
return e
}
}
}
}
}
// invites
let logs = await this.collection.getPastEvents("Invited", { fromBlock: 0, toBlock : "latest", })
for(let log of logs) {
let key = log.returnValues.key
let condition = await this.collection.methods.invite(log.returnValues.key).call()
let rawCondition = {
price: parseInt(condition.price),
start: parseInt(condition.start),
limit: parseInt(condition.limit)
}
let convertedCondition = {
eth: rawCondition.price / Math.pow(10, 18),
start: new Date(rawCondition.start * 1000),
limit: rawCondition.limit
}
let invite = {
key: log.returnValues.key,
cid: ipfsh.dtoc(log.returnValues.cid),
condition: {
raw: rawCondition,
converted: convertedCondition
}
}
if (invite.key === "0x0000000000000000000000000000000000000000000000000000000000000000") {
invite.list = []
invite.proof = []
invite.invited = true
} else {
let res = await axios.get("https://ipfs.io/ipfs/" + invite.cid).then((r) => {
return r.data
})
invite.list = res.addresses
let list = new Invitelist(invite.list)
invite.proof = list.proof(this.account)
invite.invited = list.verify(this.account, invite.proof)
}
this._invites[key] = invite
}
}
async config() {
// config
let config = await this.collection.methods.config().call()
let rawConfig = {
placeholder: config.placeholder ? config.placeholder : "ipfs://bafkreieqcdphcfojcd2vslsxrhzrjqr6cxjlyuekpghzehfexi5c3w55eq",
base: config.base,
supply: parseInt(config.supply),
permanent: config.permanent
}
return {
raw: rawConfig,
converted: this.convert(rawConfig)
}
}
async placeholder() {
let config = await this.config()
let p = await axios.get(config.converted.placeholder).then((r) => {
return r.data
})
return {
raw: p,
converted: this.convert(p)
}
}
nextId() {
return this.collection.methods.nextId().call()
}
name() {
return this.collection.methods.name().call()
}
symbol() {
return this.collection.methods.symbol().call()
}
async mint (key, count) {
if (!key) { key = "0x0000000000000000000000000000000000000000000000000000000000000000" }
let auth = { key, proof: this._invites[key].proof }
let cost = "" + this._invites[key].condition.raw.price * count
let tx = await this.api.mint(auth, count).send({ value: cost })
let tokenIds;
if (this.key) {
tokenIds = tx.logs.map((log) => {
return "" + parseInt(Number(log.topics[3]), 10)
})
} else {
let Transfers = (Array.isArray(tx.events.Transfer) ? tx.events.Transfer : [tx.events.Transfer])
tokenIds = Transfers.map((t) => {
return "" + t.returnValues.tokenId
})
}
let net = await this.web3.eth.net.getNetworkType()
return tokenIds.map((tokenId) => {
let urls = {
rinkeby: {
opensea: `https://testnets.opensea.io/assets/${this.address}/${tokenId}`,
rarible: `https://rinkeby.rarible.com/token/${this.address}:${tokenId}`
},
main: {
opensea: `https://opensea.io/assets/${this.address}/${tokenId}`,
rarible: `https://rarible.com/token/${this.address}:${tokenId}`
}
}
return {
tokenId,
links: urls[net]
}
})
}
async calc(invite) {
let { gas, price } = await this.cost()
console.log("#", gas, price)
let currency = this.currency
return traverse(invite).map(function (x) {
if (this.isLeaf && this.key === "eth") {
this.parent.node[currency] = this.parent.node.eth * price
}
})
}
async myInvites() {
let i = JSON.parse(JSON.stringify(this._invites))
for(let key in i) {
if (!i[key].invited) {
delete i[key]
}
}
return i;
}
async invites() {
let i = JSON.parse(JSON.stringify(this._invites))
return i
}
async invite(key) {
let k = (key ? key : "0x0000000000000000000000000000000000000000000000000000000000000000")
return this._invites[k]
}
async get(tokenId) {
let r
let tokenURI
let config = await this.config()
let placeholder = await this.placeholder()
if (config.converted.base) {
tokenURI = `${config.converted.base}${tokenId}.json`
r = await axios.get(tokenURI).then((r) => {
return r.data
})
} else if (config.converted.placeholder) {
tokenURI = config.raw.placeholder
r = placeholder.raw
} else {
tokenURI = config.raw.placeholder
r = placeholder.raw
}
let converted = this.convert(r)
return {
tokenURI: tokenURI,
raw: r,
converted: converted
}
}
async logs(eventName, options) {
if (!eventName) eventName = "allEvents"
let o = Object.assign({
fromBlock: 0,
toBlock: 'latest'
}, options)
let events = await this.collection.getPastEvents(eventName, o)
return events;
}
// UTIL
convert(raw) {
let r = JSON.parse(JSON.stringify(raw))
return traverse(r).map(function (x) {
if (this.isLeaf && typeof x === 'string' && x.startsWith("ipfs://")) {
this.update("https://ipfs.io/ipfs/" + x.replace("ipfs://", ""))
}
})
}
async cost() {
let net = await this.web3.eth.net.getNetworkType()
let [gas, price] = await Promise.all([
axios.get("https://ethgasstation.info/api/ethgasAPI.json").then((r) => {
delete r.data.gasPriceRange
return r.data
}),
axios.get(`https://api.coingecko.com/api/v3/coins/markets?vs_currency=${this.currency}&ids=ethereum`).then((r) => {
return r.data
}).then((r) => {
return r[0].current_price
})
])
return { gas, price }
}
async estimate(gas) {
let cost = await this.cost()
let eth = {}
let fiat = {}
// gwei/gas
for(let speed of ["fastest", "fast", "average", "safeLow"]) {
eth[speed] = cost.gas[speed] * gas / Math.pow(10, 10)
fiat[speed] = eth[speed] * cost.price
}
return {
eth,
[this.currency]: fiat
}
}
parseURL (url) {
let u = new URL(url)
let hash = u.hash
if (!hash) return {}
hash.trim();
if(hash[0] === "#") hash = hash.slice(1);
let items = hash.split("&");
return items.reduce((res, item) => {
const pair = item.split("=");
res[pair[0]] = pair[1];
return res;
}, {})
}
}
module.exports = F0