· 4 years ago · Aug 19, 2021, 07:04 PM
1const nacl = require('tweetnacl')
2const https = require('https')
3
4function byteToHexString(uint8arr) {
5 if (!uint8arr) {
6 return '';
7 }
8
9 let hexStr = '';
10 const radix = 16;
11 const magicNumber = 0xff;
12 for (let i = 0; i < uint8arr.length; i++) {
13 let hex = (uint8arr[i] & magicNumber).toString(radix);
14 hex = (hex.length === 1) ? '0' + hex : hex;
15 hexStr += hex;
16 }
17
18 return hexStr;
19}
20
21function hexStringToByte(str) {
22 if (typeof str !== 'string') {
23 throw new TypeError('Wrong data type passed to convertor. Hexadecimal string is expected');
24 }
25 const twoNum = 2;
26 const radix = 16;
27 const uInt8arr = new Uint8Array(str.length / twoNum);
28 for (let i = 0, j = 0; i < str.length; i += twoNum, j++) {
29 uInt8arr[j] = parseInt(str.substr(i, twoNum), radix);
30 }
31 return uInt8arr;
32}
33
34function hex2ascii(hexx) {
35 const hex = hexx.toString();
36 let str = '';
37 for (let i = 0; (i < hex.length && hex.substr(i, 2) !== '00'); i += 2)
38 str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
39 return str;
40}
41
42// insert your api keys
43const publicKey = "c83bb63ddbeb01ce58a653f27be220cb630e6c9efe000e05fe4f5ffd97401595";
44const secretKey = "704c5ed365fb482edc462b7c3578083911c4477c5505f4762a09afcd94676777c83bb63ddbeb01ce58a653f27be220cb630e6c9efe000e05fe4f5ffd97401595";
45const host = 'api.dmarket.com';
46
47function getFirstOfferFromMarket() {
48 const requestOptions = {
49 host: host,
50 path: '/exchange/v1/market/items?gameId=a8db&limit=1¤cy=USD',
51 method: 'GET',
52 };
53
54 // you can use a more high-level wrapper for requests instead of native https.request
55 // check https://github.com/axios/axios as an example
56 return new Promise(function(resolve, reject) {
57 const request = https.request(requestOptions, (response) => {
58 let body = [];
59 response.on('data', function(chunk) {
60 body.push(chunk);
61 });
62 // resolve on end
63 response.on('end', function() {
64 try {
65 body = JSON.parse(Buffer.concat(body).toString());
66 } catch(e) {
67 reject(e);
68 }
69 resolve(body['objects'][0]);
70 });
71 });
72 request.end();
73 });
74}
75
76function buildTargetBodyFromOffer(offer) {
77 return {
78 "targets": [
79 {
80 "amount": 1, "gameId": offer.gameId, "price": {"amount": "2", "currency": "USD"},
81 "attributes": {
82 "gameId": offer.gameId, "categoryPath": offer.extra.categoryPath, "title": offer.title,
83 "name": offer.title,
84 "image": offer.image,
85 "ownerGets": {"amount": "1", "currency": "USD"}
86 }
87 }]
88 }
89}
90
91function sign(string) {
92 const signatureBytes = nacl.sign(new TextEncoder('utf-8').encode(string), hexStringToByte(secretKey));
93 return byteToHexString(signatureBytes).substr(0,128);
94}
95
96function sendNewTargetRequest(requestOptions, targetRequestBody) {
97 const req = https.request(requestOptions, (response) => {
98 console.log('statusCode:', response.statusCode);
99 response.on('data', (responseBodyBytes) => {
100 console.log(hex2ascii(byteToHexString(responseBodyBytes)));
101 });
102 });
103
104 req.on('error', (e) => {
105 console.error(e);
106 });
107
108 req.write(targetRequestBody);
109 req.end();
110}
111
112async function buyItem(offerId, price) {
113 const method = "PATCH";
114 const apiUrlPath = "/exchange/v1/offers-buy";
115 const targetRequestBody = JSON.stringify({
116 "offers": [
117 {
118 "offerId": offerId,
119 "price": {
120 "amount": price,
121 "currency": "USD"
122 },
123 type: "dmarket"
124 }
125 ]
126 })
127 console.log(targetRequestBody);
128 const timestamp = Math.floor(new Date().getTime() / 1000);
129 const stringToSign = method + apiUrlPath + targetRequestBody + timestamp;
130 const signature = sign(stringToSign);
131 const requestOptions = {
132 host: host,
133 path: apiUrlPath,
134 method: method,
135 headers: {
136 "X-Api-Key": publicKey,
137 "X-Request-Sign": "dmar ed25519 " + signature,
138 "X-Sign-Date": timestamp,
139 'Content-Type': 'application/json',
140 }
141 };
142
143 sendNewTargetRequest(requestOptions, targetRequestBody);
144}
145
146async function getItems() {
147 const method = "GET";
148 const apiUrlPath = "/exchange/v1/user/items";
149 const targetRequestBody = JSON.stringify({
150 "gameId": "a8db",
151 "currency": "USD"
152 })
153 console.log(targetRequestBody);
154 const timestamp = Math.floor(new Date().getTime() / 1000);
155 const stringToSign = method + apiUrlPath + targetRequestBody + timestamp;
156 const signature = sign(stringToSign);
157 const requestOptions = {
158 host: host,
159 path: apiUrlPath,
160 method: method,
161 headers: {
162 "X-Api-Key": publicKey,
163 "X-Request-Sign": "dmar ed25519 " + signature,
164 "X-Sign-Date": timestamp,
165 'Content-Type': 'application/json',
166 }
167 };
168
169 sendNewTargetRequest(requestOptions, targetRequestBody);
170}
171
172
173BuyItem("f82a3a54-8145-4c6a-9b29-5f6cdd3ea43a", "1");
174
175//getItems()