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
/
publishAndFetchRestricted.js
65 lines (48 loc) · 1.87 KB
/
publishAndFetchRestricted.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
const Mam = require('../lib/mam.client.js')
const { asciiToTrytes, trytesToAscii } = require('@iota/converter')
const mode = 'restricted'
const secretKey = 'VERYSECRETKEY'
const provider = 'https://nodes.devnet.iota.org'
const mamExplorerLink = `https://mam-explorer.firebaseapp.com/?provider=${encodeURIComponent(provider)}&mode=${mode}&key=${secretKey.padEnd(81, '9')}&root=`
// Initialise MAM State
let mamState = Mam.init(provider)
// Set channel mode
mamState = Mam.changeMode(mamState, mode, secretKey)
// 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)
console.log('Published', packet, '\n');
return message.root
}
const publishAll = async () => {
const root = await publish({
message: 'Message from Alice',
timestamp: (new Date()).toLocaleString()
})
await publish({
message: 'Message from Bob',
timestamp: (new Date()).toLocaleString()
})
await publish({
message: 'Message from Charlie',
timestamp: (new Date()).toLocaleString()
})
return root
}
// Callback used to pass data out of the fetch
const logData = data => console.log('Fetched and parsed', JSON.parse(trytesToAscii(data)), '\n')
publishAll()
.then(async root => {
// Output asyncronously using "logData" callback function
await Mam.fetch(root, mode, secretKey, logData)
// Output syncronously once fetch is completed
const result = await Mam.fetch(root, mode, secretKey)
result.messages.forEach(message => console.log('Fetched and parsed', JSON.parse(trytesToAscii(message)), '\n'))
console.log(`Verify with MAM Explorer:\n${mamExplorerLink}${root}\n`);
})