This repository was archived by the owner on Sep 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
113 lines (95 loc) · 2.62 KB
/
index.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
/* eslint-disable no-magic-numbers */
/**
* Decentralized Record of Value
* DRV200: Non-Fungible Record
*/
const { capitalizeSlug } = require('cryptography-utilities');
const isValid = require('./validations');
module.exports = ({ drv, peers, serviceEvents }) => {
/*
* Import DRV100 for its transfer logic.
*/
const DRVContract = require('drv100')({
drv,
peers,
serviceEvents
});
/**
* Define a contract that: Accepts an encoded string as
* the DRV value instead of a number, creates a file,
* populates it with the encoded content as formatted JSON,
* then generates a user-friendly magnet link for distributed
* access.
*/
const Contract = async ({
senderAddress,
recipientAddress,
usdValue,
drvValue = 'data:drv/text;text,Hello world!'
}) => {
const encoding = drvValue.substring(9, 13) === 'text' ? 'text' : 'json';
const drvContent = drvValue.split(`;${encoding}`);
const contentType = drvContent[0].replace(/data:drv\//, '');
const content = encoding === 'text'
? drvValue.split(/data\:drv\/.*;text,/)[1]
: drvValue.split(/data\:drv\/.*;json,/)[1];
if (
drvValue.substring(0, 9) !== 'data:drv/' ||
!isValid(JSON.parse(content))
) return false;
if (encoding === 'text') {
/**
* Save text records directly on-chain
*/
// eslint-disable-next-line no-param-reassign
drvValue = `::magnet:?xt=urn:drv/text&dn=${encodeURIComponent(content)}&ts=${Date.now()}`;
} else {
/**
* Cache JSON records in DSS
*/
const file = await drv.onHttpPost(
{
method: 'store',
body: {
content
},
route: {
path: 'fs'
},
path: 'store'
},
{
status: code => ({
end: () => ({
error: {
code,
message: '<DRV200> Contract error (POST).'
}
})
}),
send: body => ({
status: 200,
success: true,
data: body
})
}
);
// TODO: Flatten nested `onHttpPost` responses
const fileName = file.data.data.split('/')[1];
// eslint-disable-next-line no-param-reassign
drvValue = `::magnet:?xt=urn:drv/${contentType}:${fileName}&dn=${capitalizeSlug(contentType)}`;
}
/**
* Invoke the modified DRV100 with the encoded record.
*/
return DRVContract({
senderAddress,
recipientAddress,
contract: 'DRV200',
usdValue,
drvValue,
isDrv: true
});
};
return Contract;
};