This repository has been archived by the owner on Dec 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
smart_contracts.cljs
292 lines (238 loc) · 11.6 KB
/
smart_contracts.cljs
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
(ns district.server.smart-contracts
(:require [cljs-web3.core :as web3]
[cljs-web3.eth :as web3-eth]
[cljs-web3.utils :refer [js->cljkk camel-case]]
[cljs.core.async :refer [<! >! timeout]]
[cljs.core.match :refer-macros [match]]
[cljs.nodejs :as nodejs]
[cljs.pprint]
[cljs.spec.alpha :as s]
[clojure.string :as string]
[district.server.config :refer [config]]
[district.server.web3 :refer [web3]]
[mount.core :as mount :refer [defstate]])
(:require-macros [cljs.core.async.macros :refer [go-loop]]))
(declare start)
(defstate smart-contracts :start (start (merge (:smart-contracts @config)
(:smart-contracts (mount/args)))))
(def fs (nodejs/require "fs"))
(def process (nodejs/require "process"))
(def deasync (nodejs/require "deasync"))
(defn contract [contract-key]
(get @(:contracts @smart-contracts) contract-key))
(defn contract-address [contract-key]
(:address (contract contract-key)))
(defn contract-name [contract-key]
(:name (contract contract-key)))
(defn contract-abi [contract-key]
(:abi (contract contract-key)))
(defn contract-bin [contract-key]
(:bin (contract contract-key)))
(declare contract-call)
(defn instance
([contract-key]
(:instance (contract contract-key)))
([contract-key contract-key-or-addr]
(web3-eth/contract-at @web3 (contract-abi contract-key) (if (keyword? contract-key-or-addr)
(contract-address contract-key-or-addr)
contract-key-or-addr))))
(defn update-contract! [contract-key contract]
(swap! (:contracts @smart-contracts) update contract-key merge contract))
(defn- fetch-contract [file-name & [{:keys [:path :optional?]}]]
(let [path (or path (str (.cwd process) "/resources/public/contracts/build/"))
file-path (str path file-name)
exists? (if optional?
(.existsSync fs file-path)
true)]
(when exists?
(.readFileSync fs file-path "utf-8"))))
(defn- fetch-abi [contract-name & [opts]]
(js/JSON.parse (fetch-contract (str contract-name ".abi"))))
(defn- fetch-bin [contract-name & [opts]]
(fetch-contract (str contract-name ".bin") opts))
(defn load-contract-files [contract {:keys [:contracts-build-path]}]
(let [abi (fetch-abi (:name contract) {:path contracts-build-path})
bin (fetch-bin (:name contract) {:path contracts-build-path
:optional? true})]
(merge contract
{:abi abi
:bin bin
:instance (web3-eth/contract-at @web3 abi (:address contract))})))
(defn start [{:keys [contracts-build-path :contracts-var print-gas-usage?] :as opts}]
(merge
{:contracts (atom (into {} (map (fn [[k v]]
[k (load-contract-files v opts)])
@contracts-var)))}
opts))
(defn link-library [bin placeholder library-address]
(string/replace bin placeholder (subs library-address 2)))
(defn link-contract-libraries [smart-contracts bin library-placeholders]
(reduce (fn [bin [placeholder replacement]]
(let [address (if (keyword? replacement)
(get-in smart-contracts [replacement :address])
replacement)]
(link-library bin placeholder address)))
bin library-placeholders))
(defn- handle-deployed-contract! [contract-key contract abi tx-hash]
(let [{:keys [:gas-used :block-number :contract-address]} (web3-eth/get-transaction-receipt @web3 tx-hash)
contract (merge contract {:instance (web3-eth/contract-at @web3 abi contract-address)
:address contract-address})]
(when (and gas-used block-number)
(update-contract! contract-key contract)
(when (:print-gas-usage? @smart-contracts)
(println (:name contract) contract-address (.toLocaleString gas-used)))
contract)))
(defn- deploy-smart-contract* [contract-key {:keys [:placeholder-replacements :arguments]
:as opts} callback]
(let [{:keys [:abi :bin] :as contract} (load-contract-files (contract contract-key) @smart-contracts)]
(when-not bin
(throw (js/Error. (str "Contract " contract-key " is missing bin"))))
(let [opts (merge {:data (str "0x" (link-contract-libraries @(:contracts @smart-contracts) bin placeholder-replacements))
:gas 4000000}
(when-not (:from opts)
{:from (first (web3-eth/accounts @web3))})
opts)
Contract (apply web3-eth/contract-new @web3 abi (into (vec arguments) [(select-keys opts [:from :to :gas-price :gas
:value :data :nonce
:condition])]))
tx-hash (aget Contract "transactionHash")
filter-id (atom nil)]
(if-not (fn? callback)
(handle-deployed-contract! contract-key contract abi tx-hash)
(reset!
filter-id
(web3-eth/filter
@web3
"latest"
(fn [err]
(when err
(callback err))
(try
(when-let [contract (handle-deployed-contract! contract-key contract abi tx-hash)]
(web3-eth/stop-watching! @filter-id)
;; reset is needed, otherwise web3 crashes with "Can't connect to" on next request
;; Reasons unknown. Needed only because of deasync hack
(web3/reset @web3)
(callback nil contract))
(catch js/Error err
(callback err))))))))))
(def deploy-smart-contract-deasynced (deasync deploy-smart-contract*))
(defn deploy-smart-contract! [& args]
(if (:auto-mining? @smart-contracts)
(apply deploy-smart-contract* args)
(apply deploy-smart-contract-deasynced args)))
(defn write-smart-contracts! []
(let [{:keys [:ns :file :name]} (meta (:contracts-var @smart-contracts))]
(.writeFileSync fs file
(str "(ns " ns ") \n\n"
"(def " name " \n"
(as-> @(:contracts @smart-contracts) $
(map (fn [[k v]]
[k (dissoc v :instance :abi :bin)]) $)
(into {} $)
;; cljs.pprint/write won't compile with simple optimisations
;; therefore must be required only in dev environment
(cljs.pprint/write $ :stream nil))
")"))))
(defn- handle-contract-call
([method tx-hash]
(handle-contract-call method tx-hash false))
([method tx-hash print-gas-usage?]
(let [{:keys [:gas-used :block-number :status]} (web3-eth/get-transaction-receipt @web3 tx-hash)]
(when (and gas-used block-number)
(when print-gas-usage?
(println method (.toLocaleString gas-used) (if (zero? status) "failed" "")))
gas-used))))
(defn- instance-from-arg [contract]
(cond
(keyword? contract) (instance contract)
(sequential? contract) (instance (first contract) (second contract))
:else contract))
(defn contract-call* [contract-key method & args]
"contract-key parameter can be one of:
- keyword :some-contract
- tuple of keyword and address [:some-contract 0x1234...]
- instance SomeContract"
(let [deasync? (fn? (last args))
callback (when deasync? (last args))
args (if deasync? (drop-last args) args)
contract (instance-from-arg contract-key)
last-arg (last args)
args (if (and (map? last-arg)
(not (:from last-arg)))
(concat (butlast args) [(merge last-arg {:from (first (web3-eth/accounts @web3))})])
args)
result (apply web3-eth/contract-call contract method args)
filter-id (atom nil)]
(if-not (fn? callback)
(do
(when (and (:print-gas-usage? @smart-contracts)
(map? (last args))
(string? result))
(handle-contract-call method result))
result)
(reset! filter-id
(web3-eth/filter
@web3
"latest"
(fn [err]
(when err
(callback err))
(try
(when (and (string? result)
(map? (last args)))
(loop [gas-used (handle-contract-call method result)]
(when-not gas-used
(recur (handle-contract-call method result (:print-gas-usage? @smart-contracts))))))
(web3-eth/stop-watching! @filter-id)
(callback nil result)
(catch js/Error err
(callback err)))))))))
(def contract-call-deasynced (deasync contract-call*))
(defn contract-call [& args]
(if (:auto-mining? @smart-contracts)
(apply contract-call* args)
(apply contract-call-deasynced args)))
(defn contract-event-in-tx [tx-hash contract event-name & args]
(let [instance (instance-from-arg contract)
event-filter (apply web3-eth/contract-call instance event-name args)
formatter (aget event-filter "formatter")
contract-addr (aget instance "address")
{:keys [:logs]} (web3-eth/get-transaction-receipt @web3 tx-hash)
signature (aget event-filter "options" "topics" 0)]
(reduce (fn [result log]
(when (= signature (first (:topics log)))
(let [{:keys [:address] :as evt} (js->clj (formatter (clj->js log)) :keywordize-keys true)]
(when (= contract-addr address)
(reduced (js->cljkk evt))))))
nil
logs)))
(defn contract-events-in-tx [tx-hash contract event-name & args]
(let [instance (instance-from-arg contract)
event-filter (apply web3-eth/contract-call instance event-name args)
formatter (aget event-filter "formatter")
contract-addr (aget instance "address")
{:keys [:logs]} (web3-eth/get-transaction-receipt @web3 tx-hash)
signature (aget event-filter "options" "topics" 0)]
(reduce (fn [result log]
(when (= signature (first (:topics log)))
(let [{:keys [:address] :as evt} (js->clj (formatter (clj->js log)) :keywordize-keys true)]
(when (= contract-addr address)
(concat result [(js->cljkk evt)])))))
nil
logs)))
(defn replay-past-events [event-filter callback & [{:keys [:delay :transform-fn]
:or {delay 0 transform-fn identity}}]]
(let [stopped? (atom false)]
(.get event-filter (fn [err all-logs]
(when err
(throw (js/Error. err)))
(let [all-logs (transform-fn (js->cljkk all-logs))]
(go-loop [logs all-logs]
(when (and (not @stopped?)
(seq logs))
(<! (timeout delay))
(callback nil (first logs))
(recur (rest logs)))))))
(aset event-filter "stopWatching" #(reset! stopped? true)) ;; So we can detect stopWatching was called
event-filter))