This repository has been archived by the owner on Jun 7, 2023. It is now read-only.
forked from l3wi/mam.client.js
-
Notifications
You must be signed in to change notification settings - Fork 41
/
publishAndFetchPublic.html
88 lines (66 loc) · 2.89 KB
/
publishAndFetchPublic.html
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
<html>
<meta charset="utf-8" />
<head>
<title>MAM Example Publish and Fetch</title>
</head>
<body>
<div id="output"></div>
<script src="../lib/mam.web.min.js"></script>
<script>
const TRYTE_ALPHABET = '9ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const asciiToTrytes = (input) => {
let trytes = '';
for (let i = 0; i < input.length; i++) {
var dec = input[i].charCodeAt(0);
trytes += TRYTE_ALPHABET[dec % 27];
trytes += TRYTE_ALPHABET[(dec - dec % 27) / 27];
}
return trytes;
};
const trytesToAscii = (trytes) => {
let ascii = '';
for (let i = 0; i < trytes.length; i += 2) {
ascii += String.fromCharCode(TRYTE_ALPHABET.indexOf(trytes[i]) + TRYTE_ALPHABET.indexOf(trytes[i + 1]) * 27);
}
return ascii;
};
(async function () {
const mode = 'public'
const provider = 'https://nodes.devnet.iota.org'
const mamExplorerLink = `https://mam-explorer.firebaseapp.com/?provider=${encodeURIComponent(provider)}&mode=${mode}&root=`
const outputHtml = document.querySelector("#output");
// Initialise MAM State
let mamState = Mam.init(provider)
// Publish to tangle
const publish = async packet => {
// Create MAM Payload - STRING OF TRYTES
const trytes = asciiToTrytes(JSON.stringify(packet))
const message = Mam.create(mamState, trytes)
// Save new mamState
mamState = message.state
// Attach the payload
await Mam.attach(message.payload, message.address, 3, 9)
outputHtml.innerHTML += `Published: ${packet}<br/>`;
return message.root
}
const publishAll = async () => {
const root = await publish('ALICE')
await publish('BOB')
await publish('CHARLIE')
return root
}
// Callback used to pass data out of the fetch
const logData = data => outputHtml.innerHTML += `Fetched and parsed ${JSON.parse(trytesToAscii(data))}<br/>`;
const root = await publishAll();
// Output asyncronously using "logData" callback function
await Mam.fetch(root, mode, null, logData)
// Output syncronously once fetch is completed
const result = await Mam.fetch(root, mode)
result.messages.forEach(message => {
outputHtml.innerHTML += `Fetched and parsed ${JSON.parse(trytesToAscii(message))}<br/>`
});
outputHtml.innerHTML += `Verify with MAM Explorer:<br/><a target="_blank" href="${mamExplorerLink}${root}">${mamExplorerLink}${root}</a>`;
})();
</script>
</body>
</html>