Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace @root/request with fetch #20

Merged
merged 2 commits into from
Jan 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions dashfetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
(function (exports) {
"use strict";

/**
* @type {RequestInit} defaultOpts
*/
let defaultOpts = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
}

/**
* @param {String | URL | Request} url
* @param {RequestInit} opts
*/
async function dashfetch(url, opts) {
opts = Object.assign({}, defaultOpts, opts)
if (opts.body) {
opts.body = JSON.stringify(opts.body)
}

let resp = await fetch(url, opts);
if (resp.ok) {
return resp;
}

let err = new Error(
`http request was ${resp.status}, not ok. See err.response for details.`,
);
// @ts-ignore
err.response = resp.json();
throw err;
}

// @ts-ignore
exports.__dashsight_fetch = dashfetch;

if ("undefined" !== typeof module) {
module.exports = dashfetch;
}
})(("undefined" !== typeof module && module.exports) || window);
36 changes: 0 additions & 36 deletions dashrequest.js

This file was deleted.

40 changes: 17 additions & 23 deletions dashsight.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
exports.DashSight = Dashsight;

//@ts-ignore
let request = exports.__dashsight_request || require("./lib/request.js");
const dashfetch = exports.__dashsight_fetch || require('./dashfetch.js')

const DUFFS = 100000000;

Expand Down Expand Up @@ -72,7 +72,7 @@
console.warn(`warn: getBalance(pubkey) doesn't account for instantSend,`);
console.warn(` consider (await getUtxos()).reduce(countSatoshis)`);
let txUrl = `${insightBaseUrl}/addr/${address}/?noTxList=1`;
let txResp = await request({ url: txUrl, json: true });
let txResp = await dashfetch(txUrl);

/** @type {InsightBalance} */
let data = txResp.body;
Expand All @@ -82,7 +82,7 @@
/** @type {GetInstantBalance} */
insight.getInstantBalance = async function (address) {
let utxos = await insight.getUtxos(address);
let balanceDuffs = utxos.reduce(function (total, utxo) {
let balanceDuffs = utxos?.reduce(function (total, utxo) {
return total + utxo.satoshis;
}, 0);
// because 0.1 + 0.2 = 0.30000000000000004,
Expand All @@ -103,10 +103,10 @@
/** @type {GetUtxos} */
insight.getUtxos = async function (address) {
let utxoUrl = `${insightBaseUrl}/addr/${address}/utxo`;
let utxoResp = await request({ url: utxoUrl, json: true });
let utxoResp = await dashfetch(utxoUrl);

/** @type Array<InsightUtxo> */
let utxos = utxoResp.body;
let utxos = await utxoResp.json();
return utxos;
};

Expand All @@ -125,20 +125,20 @@
/** @type {GetTx} */
insight.getTx = async function (txid) {
let txUrl = `${insightBaseUrl}/tx/${txid}`;
let txResp = await request({ url: txUrl, json: true });
let txResp = await dashfetch(txUrl);

/** @type InsightTx */
let data = txResp.body;
let data = await txResp.json();
return data;
};

/** @type {GetTxs} */
insight.getTxs = async function (addr, maxPages) {
let txUrl = `${insightBaseUrl}/txs?address=${addr}&pageNum=0`;
let txResp = await request({ url: txUrl, json: true });
let txResp = await dashfetch(txUrl);

/** @type {InsightTxResponse} */
let body = txResp.body;
let body = await txResp.json();

let data = await getAllPages(body, addr, maxPages);
return data;
Expand All @@ -152,13 +152,13 @@
async function getAllPages(body, addr, maxPages) {
let pagesTotal = Math.min(body.pagesTotal, maxPages);
for (let cursor = 1; cursor < pagesTotal; cursor += 1) {
let nextResp = await request({
url: `${insightBaseUrl}/txs?address=${addr}&pageNum=${cursor}`,
json: true,
});
let nextResp = await dashfetch(
`${insightBaseUrl}/txs?address=${addr}&pageNum=${cursor}`);
nextResp = await nextResp.json();
// Note: this could still be wrong, but I don't think we have
// a better way to page so... whatever
body.txs = body.txs.concat(nextResp.body.txs);
// @ts-ignore
body.txs = body.txs.concat(nextResp?.txs);
}
return body;
}
Expand All @@ -169,20 +169,14 @@
// - https://insight.dash.org/insight-api-dash/tx/sendix
// - https://dashsight.dashincubator.dev/insight-api/tx/sendix
let instUrl = `${dashsightBaseUrl}/tx/sendix`;
let reqObj = {
let txResp = await dashfetch(instUrl, {
method: "POST",
url: instUrl,
json: true,
form: {
rawtx: hexTx,
},
};
let txResp = await request(reqObj);
});
if (!txResp.ok) {
// TODO better error check
throw new Error(JSON.stringify(txResp.body, null, 2));
}
return txResp.toJSON();
return txResp.json();
};

/** @type {ToCoreUtxos} */
Expand Down
1 change: 1 addition & 0 deletions dashsocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@
}
*/

let pingTimeout
let ws = await Eio3.connectWs(session.sid);
wsc._ws = ws;
ws._pingTimeout = null;
Expand Down
2 changes: 1 addition & 1 deletion example.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<body>
<h1>Open the Console!</h1>
<script src="https://unpkg.com/@root/[email protected]/urequest.js"></script>
<script src="./dashrequest.js"></script>
<script src="./dashfetch.js"></script>
<script src="./dashsight.js"></script>
<script src="./dashsocket.js"></script>

Expand Down
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ module.exports = require("./dashsight.js");
*/

/**
* @typedef InsightBalance
* @typedef {Object | null} InsightBalance
* @property {String} addrStr
* @property {Number} balance
* @property {Number} balanceSat
Expand Down
27 changes: 0 additions & 27 deletions lib/request.js

This file was deleted.

6 changes: 2 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
"description": "SDK for Dash's flavor of the Insight API",
"main": "index.js",
"browser": {
"./ws/index.js": "./dashsocket.js",
"./lib/request.js": "./dashrequest.js"
"./ws/index.js": "./dashsocket.js"
},
"bin": {
"dashsight-balance": "bin/balance.js",
Expand All @@ -22,11 +21,10 @@
},
"files": [
"bin",
"dashrequest.js",
"dashfetch.js",
"dashsight.js",
"dashsocket.js",
"index.js",
"lib",
"typings",
"ws"
],
Expand Down
21 changes: 8 additions & 13 deletions ws/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ let Ws = module.exports;
Ws.DashSocket = Ws;
Ws.DashSightWs = Ws; // deprecated

let request = require("../lib/request.js");

let WSClient = require("ws");

/**
Expand Down Expand Up @@ -51,23 +49,21 @@ Ws.create = function ({
let sidUrl = `${dashsocketBaseUrl}/?EIO=3&transport=polling&t=${now}`;

let cookies = await cookieStore.get(sidUrl);
let sidResp = await request({
let sidResp = await fetch(sidUrl, {
//agent: httpAgent,
url: sidUrl,
//@ts-ignore - request function is not typed correctly
headers: {
Cookie: cookies,
},
json: false,
});
if (!sidResp.ok) {
console.error(sidResp.toJSON());
console.error(await sidResp.json());
throw new Error("bad response");
}
await cookieStore.set(sidUrl, sidResp);

// ex: `97:0{"sid":"xxxx",...}`
let msg = sidResp.body;
let msg = await sidResp.json();
let colonIndex = msg.indexOf(":");
// 0 is CONNECT, which will always follow our first message
let start = colonIndex + ":0".length;
Expand Down Expand Up @@ -100,24 +96,24 @@ Ws.create = function ({
let body = `${len}:${msg}`;

let cookies = await cookieStore.get(subUrl);
let subResp = await request({
let subResp = await fetch(subUrl,
{
//agent: httpAgent,
method: "POST",
url: subUrl,
headers: {
"Content-Type": "text/plain;charset=UTF-8",
Cookie: cookies,
},
body: body,
});
if (!subResp.ok) {
console.error(subResp.toJSON());
console.error(await subResp.json());
throw new Error("bad response");
}
await cookieStore.set(subUrl, subResp);

// "ok"
return subResp.body;
return await subResp.json();
};

/*
Expand All @@ -126,10 +122,9 @@ Ws.create = function ({
let pollUrl = `${dashsocketBaseUrl}/?EIO=3&transport=polling&t=${now}&sid=${sid}`;

let cookies = await cookieStore.get(pollUrl);
let pollResp = await request({
let pollResp = await fetch(pollUrl, {
//agent: httpAgent,
method: "GET",
url: pollUrl,
headers: Object.assign(
{
Cookie: cookies,
Expand Down