· 5 years ago · Nov 30, 2019, 09:02 PM
1const Mam = require('@iota/mam')
2const { asciiToTrytes, trytesToAscii } = require('@iota/converter')
3
4const mode = 'restricted'
5const secretKey = 'PASSWORDYEHIAAAAAAA'
6const provider = 'https://nodes.devnet.iota.org'
7
8const mamExplorerLink = `https://mam-explorer.firebaseapp.com/?provider=${encodeURIComponent(provider)}&mode=${mode}&key=${secretKey.padEnd(81, '9')}&root=`
9
10// Initialise MAM State
11let mamState = Mam.init(provider)
12
13// Set channel mode
14mamState = Mam.changeMode(mamState, mode, secretKey)
15
16// Publish to tangle
17const publish = async packet => {
18 // Create MAM Payload - STRING OF TRYTES
19 const trytes = asciiToTrytes(JSON.stringify(packet))
20 const message = Mam.create(mamState, trytes)
21
22 // Save new mamState
23 mamState = message.state
24
25 // Attach the payload
26 await Mam.attach(message.payload, message.address, 3, 9)
27
28 console.log('Published', packet, '\n');
29 return message.root
30}
31
32const publishAll = async () => {
33 const root = await publish({
34 message: 'Message from Alice',
35 timestamp: (new Date()).toLocaleString()
36 })
37
38 await publish({
39 message: 'Message from Bob',
40 timestamp: (new Date()).toLocaleString()
41 })
42
43 await publish({
44 message: 'Message from Charlie',
45 timestamp: (new Date()).toLocaleString()
46 })
47
48 return root
49}
50
51// Callback used to pass data out of the fetch
52const logData = data => console.log('Fetched and parsed', JSON.parse(trytesToAscii(data)), '\n')
53
54publishAll()
55 .then(async () => {
56
57 // Output asyncronously using "logData" callback function
58 const root = Mam.getRoot(mamState)
59 console.log("the root is",root)
60 await Mam.fetch(root, mode, secretKey, logData)
61 // Output syncronously once fetch is completed
62 const result = await Mam.fetch(root, mode, secretKey)
63 result.messages.forEach(message => console.log('Fetched and parsed', JSON.parse(trytesToAscii(message)), '\n'))
64
65 console.log(`Verify with MAM Explorer:\n${mamExplorerLink}${root}\n`);
66 })