-
Notifications
You must be signed in to change notification settings - Fork 15
/
controller.js
425 lines (373 loc) · 11.7 KB
/
controller.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
/* Example of Using Marlowe Runtime with a CIP45 Wallet */
'use strict'
// Import the CIP45 support module.
import * as CardanoPeerConnect from '@fabianbormann/cardano-peer-connect'
// Use a Bech32 library for converting address formats.
import {bech32} from "bech32"
// The explorers.
let cardanoScanUrl = null
let marloweScanUrl = null
// Connection to the CIP30 wallet.
let wallet = null
// Address of the depositor.
let address = null
// Identifier for the contract.
let contractId = null
// URL for Marlowe Runtime's /contracts endpoint.
let contractUrl = null
// URL for Marlowe Runtime's /contract/*/transactions endpoint.
let transactionUrl = null
// The JSON for the Marlowe contract.
let contract = {}
// Poll every five seconds.
const delay = 5000
// One ada is one million lovelace.
const ada = 1000000
/**
* Set the wallet's address in the UI.
* @param [String] a The hexadecimal bytes for the address.
*/
function setAddress(a) {
const bytes = []
for (let c = 0; c < a.length; c += 2)
bytes.push(parseInt(a.substr(c, 2), 16))
let prefix = null
if (a[1] == "0") {
cardanoScanUrl = "https://preprod.cardanoscan.io"
marloweScanUrl = "https://preprod.marlowescan.com"
prefix = "addr_test"
} else {
cardanoScanUrl = "https://cardanoscan.io"
marloweScanUrl = "https://mainnet.marlowescan.com"
prefix = "addr"
}
address = bech32.encode(prefix, bech32.toWords(bytes), 1000)
const display = address.substr(0, 29) + "..." + address.substr(address.length - 24)
uiAddress.innerHTML = "<a href='" + cardanoScanUrl + "/address/" + a + "' target='marlowe'>" + display + "</a>"
}
/**
* Set the contract ID in the UI.
* @param [String] c The contract ID.
*/
function setContract(c) {
contractId = c
uiContractId.innerHTML = "<a href='" + marloweScanUrl + "/contractView?tab=info&contractId=" + contractId.replace("#", "%23") + "' target='marlowe'>" + contractId + "</a>"
}
/**
* Set a link to a transaction in the UI.
* @param [Element] element The UI element for the transaction.
* @param [String] tx The transaction ID.
*/
function setTx(element, tx) {
element.innerHTML = "<a href='" + cardanoScanUrl + "/transaction/" + tx + "?tab=utxo' target='marlowe'>" + tx + "</a>"
}
/**
* Make the JSON for the Marlowe contract.
*/
export function makeContract() {
contract = {
when : [
{
case : {
party : {
address : address
}
, deposits : parseInt(uiFundingAmount.value)
, of_token : {
currency_symbol : uiFundingPolicy.value
, token_name : uiFundingName.value
}
, into_account : {
role_token : uiRecipientName.innerText
}
}
, then : "close"
}
]
, timeout : Date.parse(uiDepositTime.value)
, timeout_continuation : "close"
}
console.log({contract : contract})
}
/**
* Perform an operation that requires blocking the UI.
*/
function waitCursor() {
document.body.style.cursor = "wait"
uiCreate.style.cursor = "wait"
uiDeposit.style.cursor = "wait"
uiMessage.innerText = "Working . . ."
}
/**
* Report a result and unblock the UI.
*/
function report(message) {
status(message)
uiCreate.style.cursor = "default"
uiDeposit.style.cursor = "default"
document.body.style.cursor = "default"
}
/**
* Show a status message in the UI.
* @param [String] message The message.
*/
function status(message) {
uiMessage.innerText = message
}
/**
* Build a Marlowe transaction.
* @param [String] operation The name of the operation being performed.
* @param [Object] req The HTTP request.
* @param [String] url The endpoint's URL.
* @param [String] accept The "accept" HTTP header.
* @param [Function] followup Actions to perform after the transaction is built.
*/
async function buildTransaction(operation, req, url, accept, followup) {
waitCursor()
const xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
console.log({operation : operation, status : this.status, response : this.responseText})
if (this.status == 201) {
const res = JSON.parse(this.responseText)
followup(res)
} else {
report("Transaction building failed.")
}
}
}
xhttp.open("POST", url)
xhttp.setRequestHeader("Content-Type", "application/json")
xhttp.setRequestHeader("Accept", accept)
xhttp.setRequestHeader("X-Change-Address", address)
console.log({operation : operation, request : req})
status("Building transaction.")
xhttp.send(JSON.stringify(req))
}
/**
* Create the contract.
*/
export async function createContract() {
buildTransaction(
"create"
, {
version : "v1"
, contract : contract
, roles : uiRecipientPolicy.innerText
, minUTxODeposit : 2 * ada
, metadata : {}
, tags : {}
}
, uiRuntime.innerText + "/contracts"
, "application/vendor.iog.marlowe-runtime.contract-tx-json"
, function(res) {
if (res.resource.safetyErrors.length > 0) {
report("Refusing to create contract with safety errors: " + res.resource.safetyErrors.map(x => x.detail).join(" "))
} else {
uiFundingPolicy.disabled = true
uiFundingName.disabled = true
uiFundingAmount.disabled = true
uiDepositTime.disabled = true
setContract(res.resource.contractId)
contractUrl = uiRuntime.innerText + "/" + res.links.contract
const followup = function() {
uiCreate.disabled = true
uiDeposit.disabled = false
setTx(uiCreateTx, contractId.replace(/#.*$/, ""))
}
submitTransaction(res.resource.tx.cborHex, contractUrl, waitForConfirmation(contractUrl, followup))
}
}
)
}
/**
* Apply inputs to the contract.
*/
async function applyInputs(operation, inputs, followup) {
buildTransaction(
operation
, {
version : "v1"
, inputs: inputs
, metadata : {}
, tags : {}
}
, contractUrl + "/transactions"
, "application/vendor.iog.marlowe-runtime.apply-inputs-tx-json"
, function(res) {
transactionUrl = uiRuntime.innerText + "/" + res.links.transaction
const tx = res.resource.transactionId
submitTransaction(res.resource.tx.cborHex, transactionUrl, waitForConfirmation(transactionUrl, followup(tx)))
}
)
}
/**
* Deposit funds into the contract.
*/
export async function depositFunds() {
applyInputs(
"deposit"
, [
{
input_from_party : {address : address}
, that_deposits : parseInt(uiFundingAmount.value)
, of_token : {currency_symbol : uiFundingPolicy.value, token_name : uiFundingName.value}
, into_account: {role_token : uiRecipientName.innerText}
}
]
, function(tx) {
return function() {
uiCreate.disabled = false
uiDeposit.disabled = true
setTx(uiDepositTx, tx)
}
}
)
}
/**
* Submit a transaction.
* @param [String] cborHex The hexadecimal-encoded CBOR for the transaction.
* @param [String] url The URL for the Marlowe Runtime endpoint for submitting the transaction.
* @param [Function] wait Action to be performed for waiting for the confirmation.
*/
function submitTransaction(cborHex, url, wait) {
const stateCreate = uiCreate.disabled
const stateDeposit = uiDeposit.disabled
uiCreate.disabled = true
uiDeposit.disabled = true
status("Signing transaction.")
wallet.signTx(cborHex, true).then(function(witness) {
const xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
console.log({operation : "submit", status : this.status, response : this.responseText})
if (this.status == 202) {
setTimeout(wait, delay)
} else {
uiCreate.disabled = stateCreate
uiDeposit.disabled = stateDeposit
report("Transaction submission failed.")
}
}
}
xhttp.open("PUT", url)
xhttp.setRequestHeader("Content-Type", "application/json")
const req = {
type : "ShelleyTxWitness BabbageEra"
, description : ""
, cborHex : witness
}
console.log({operation : "submit", request : req})
status("Submitting transaction.")
xhttp.send(JSON.stringify(req))
}).catch(function(error) {
uiCreate.disabled = stateCreate
uiDeposit.disabled = stateDeposit
report(error)
})
}
/**
* Wait for a transaction to be confirmed.
*/
function waitForConfirmation(url, followup) {
return function() {
const xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
console.log({operation : "wait", status : this.status, response : this.responseText})
if (this.status == 200) {
const res = JSON.parse(this.responseText)
if (res.resource.status == "confirmed") {
setTimeout(function() {
followup()
report("Transaction confirmed.")
}, delay)
} else if (res.resource.status == "submitted") {
setTimeout(waitForConfirmation(url, followup), delay)
} else {
report("Confirmation failed.")
}
}
}
}
xhttp.open("GET", url)
console.log({operation : "wait"})
status("Waiting for confirmation.")
xhttp.send()
}
}
/**
* Initialize the application.
*/
export async function initialize() {
if (window.location.search) {
const params = new URLSearchParams(window.location.search)
uiRuntime.innerText = params.get("runtimeUrl")
uiRecipientPolicy.innerText = params.get("recipientPolicy")
uiRecipientName.innerText = params.get("recipientName")
}
if (uiRuntime.innerText == "")
uiRuntime.innerText = "http://127.0.0.1:3780"
if (uiRecipientPolicy.innerText == "")
uiRecipientPolicy.innerText = "d441227553a0f1a965fee7d60a0f724b368dd1bddbc208730fccebcf" // Anyone can mint.
if (uiRecipientName.innerText == "")
uiRecipientName.innerText = "Token"
uiDepositTime.value = (new Date(new Date() - ((new Date()).getTimezoneOffset() - 24 * 60) * 60 * 1000)).toISOString().replace("Z", "")
uiFundingPolicy.disabled = false
uiFundingName.disabled = false
uiFundingAmount.disabled = false
uiDepositTime.disabled = false
uiCreate.disabled = true
uiDeposit.disabled = true
const dAppConnect = new CardanoPeerConnect.DAppPeerConnect({
dAppInfo: {
name: "Marlowe CIP45 Example",
url: "https://examples.marlowe.app:8080/cip45.html"
},
onApiInject: function(name, addr) {
status("CardanoConnect API injected for wallet \"" + name + "\".")
cardano[name].enable().then(function(n) {
wallet = n
wallet.getChangeAddress().then(function(a) {
setAddress(a)
makeContract()
uiCreate.disabled = false
}).catch(function(error) {
uiCreate.disabled = true
report(error)
})
}).catch(function(error) {
report(error)
})
},
onApiEject: function(name, addr) {
status("CardanoConnect API ejected for wallet \"" + name + "\".")
},
verifyConnection: function(walletInfo, callback) {
status("Verifying connection for wallet \"" + walletInfo.name + "\" at " + walletInfo.address + ".")
callback(true, true)
},
onConnect: function(addr, walletInfo) {
uiWallet.innerText = addr
status("Connected to wallet at " + addr + ".")
uiCreate.disabled = true
},
onDisconnect: function() {
uiWallet.innerText = ""
status("Disconnected from wallet.")
uiCreate.disabled = true
},
})
uiMeerkat.innerText = dAppConnect.getAddress()
}
/**
* Restart the application.
*/
export async function restart() {
document.body.style.cursor = "default"
uiContractId.innerText = ""
uiCreateTx.innerText = ""
uiDepositTx.innerText = ""
uiMessage.innerText = ""
initialize()
}