@1money/protocol-ts-sdk 1.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/settings.local.json +14 -0
- package/CLAUDE.md +77 -0
- package/README.md +600 -0
- package/es/api/accounts/index.d.ts +20 -0
- package/es/api/accounts/types.d.ts +9 -0
- package/es/api/chain/index.d.ts +12 -0
- package/es/api/chain/types.d.ts +3 -0
- package/es/api/checkpoints/index.d.ts +26 -0
- package/es/api/checkpoints/types.d.ts +33 -0
- package/es/api/constants.d.ts +9 -0
- package/es/api/index.d.ts +31 -0
- package/es/api/index.js +593 -0
- package/es/api/state/index.d.ts +12 -0
- package/es/api/state/types.d.ts +7 -0
- package/es/api/tokens/index.d.ts +62 -0
- package/es/api/tokens/types.d.ts +130 -0
- package/es/api/transactions/index.d.ts +35 -0
- package/es/api/transactions/types.d.ts +25 -0
- package/es/api/types.d.ts +18 -0
- package/es/client/core.d.ts +109 -0
- package/es/client/index.d.ts +21 -0
- package/es/client/index.js +373 -0
- package/es/index.d.ts +20 -0
- package/es/index.js +1490 -0
- package/es/utils/address.d.ts +15 -0
- package/es/utils/index.d.ts +6 -0
- package/es/utils/index.js +841 -0
- package/es/utils/interface.d.ts +7 -0
- package/es/utils/safePromise.d.ts +4 -0
- package/es/utils/sign.d.ts +15 -0
- package/es/utils/txHash.d.ts +2 -0
- package/es/utils/typeof.d.ts +2 -0
- package/lib/api/accounts/index.d.ts +20 -0
- package/lib/api/accounts/types.d.ts +9 -0
- package/lib/api/chain/index.d.ts +12 -0
- package/lib/api/chain/types.d.ts +3 -0
- package/lib/api/checkpoints/index.d.ts +26 -0
- package/lib/api/checkpoints/types.d.ts +33 -0
- package/lib/api/constants.d.ts +9 -0
- package/lib/api/index.d.ts +31 -0
- package/lib/api/index.js +692 -0
- package/lib/api/state/index.d.ts +12 -0
- package/lib/api/state/types.d.ts +7 -0
- package/lib/api/tokens/index.d.ts +62 -0
- package/lib/api/tokens/types.d.ts +130 -0
- package/lib/api/transactions/index.d.ts +35 -0
- package/lib/api/transactions/types.d.ts +25 -0
- package/lib/api/types.d.ts +18 -0
- package/lib/client/core.d.ts +109 -0
- package/lib/client/index.d.ts +21 -0
- package/lib/client/index.js +434 -0
- package/lib/index.d.ts +20 -0
- package/lib/index.js +1591 -0
- package/lib/utils/address.d.ts +15 -0
- package/lib/utils/index.d.ts +6 -0
- package/lib/utils/index.js +937 -0
- package/lib/utils/interface.d.ts +7 -0
- package/lib/utils/safePromise.d.ts +4 -0
- package/lib/utils/sign.d.ts +15 -0
- package/lib/utils/txHash.d.ts +2 -0
- package/lib/utils/typeof.d.ts +2 -0
- package/package.json +111 -0
- package/public/favicon.ico +0 -0
- package/public/logo.png +0 -0
- package/umd/1money-protocol-ts-sdk.min.js +2 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,1591 @@
|
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var axios$1=require('axios'),viem=require('viem'),rlp=require('@ethereumjs/rlp');/******************************************************************************
|
|
2
|
+
Copyright (c) Microsoft Corporation.
|
|
3
|
+
|
|
4
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
5
|
+
purpose with or without fee is hereby granted.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
8
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
9
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
10
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
11
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
12
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
13
|
+
PERFORMANCE OF THIS SOFTWARE.
|
|
14
|
+
***************************************************************************** */
|
|
15
|
+
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
var __assign = function() {
|
|
19
|
+
__assign = Object.assign || function __assign(t) {
|
|
20
|
+
for (var s, i = 1, n = arguments.length; i < n; i++) {
|
|
21
|
+
s = arguments[i];
|
|
22
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
|
|
23
|
+
}
|
|
24
|
+
return t;
|
|
25
|
+
};
|
|
26
|
+
return __assign.apply(this, arguments);
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
function __rest(s, e) {
|
|
30
|
+
var t = {};
|
|
31
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
32
|
+
t[p] = s[p];
|
|
33
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
34
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
35
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
36
|
+
t[p[i]] = s[p[i]];
|
|
37
|
+
}
|
|
38
|
+
return t;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function __awaiter(thisArg, _arguments, P, generator) {
|
|
42
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
43
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
44
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
45
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
46
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
47
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function __generator(thisArg, body) {
|
|
52
|
+
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
53
|
+
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
54
|
+
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
55
|
+
function step(op) {
|
|
56
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
57
|
+
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
58
|
+
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
59
|
+
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
60
|
+
switch (op[0]) {
|
|
61
|
+
case 0: case 1: t = op; break;
|
|
62
|
+
case 4: _.label++; return { value: op[1], done: false };
|
|
63
|
+
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
64
|
+
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
65
|
+
default:
|
|
66
|
+
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
67
|
+
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
68
|
+
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
69
|
+
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
70
|
+
if (t[2]) _.ops.pop();
|
|
71
|
+
_.trys.pop(); continue;
|
|
72
|
+
}
|
|
73
|
+
op = body.call(thisArg, _);
|
|
74
|
+
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
75
|
+
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function __spreadArray(to, from, pack) {
|
|
80
|
+
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
|
81
|
+
if (ar || !(i in from)) {
|
|
82
|
+
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
|
|
83
|
+
ar[i] = from[i];
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return to.concat(ar || Array.prototype.slice.call(from));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
|
90
|
+
var e = new Error(message);
|
|
91
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
92
|
+
};/**
|
|
93
|
+
* Derives the token account address given the wallet address and mint address.
|
|
94
|
+
*
|
|
95
|
+
* Address is 20 byte, 160 bits. Let's say if we want to support 50 billion
|
|
96
|
+
* accounts on 1money. That's about 36 bits. There are 124 bits remaining. In
|
|
97
|
+
* other words, the collision probability is 1/2^124, which is very very low.
|
|
98
|
+
* So, we will be fine to just use the hash of the wallet address and mint
|
|
99
|
+
* address to derive the token account address.
|
|
100
|
+
*
|
|
101
|
+
* @param walletAddress - The wallet address (20 bytes)
|
|
102
|
+
* @param mintAddress - The mint address (20 bytes)
|
|
103
|
+
* @returns The derived token account address
|
|
104
|
+
*/
|
|
105
|
+
function deriveTokenAddress(walletAddress, mintAddress) {
|
|
106
|
+
var walletBytes = walletAddress.startsWith('0x')
|
|
107
|
+
? viem.hexToBytes(walletAddress)
|
|
108
|
+
: viem.stringToBytes(walletAddress);
|
|
109
|
+
var mintBytes = mintAddress.startsWith('0x')
|
|
110
|
+
? viem.hexToBytes(mintAddress)
|
|
111
|
+
: viem.stringToBytes(mintAddress);
|
|
112
|
+
var combined = new Uint8Array(walletBytes.length + mintBytes.length);
|
|
113
|
+
combined.set(walletBytes, 0);
|
|
114
|
+
combined.set(mintBytes, walletBytes.length);
|
|
115
|
+
var hashHex = viem.keccak256(combined);
|
|
116
|
+
var hashBytes = viem.hexToBytes(hashHex);
|
|
117
|
+
var addressBytes = hashBytes.slice(12);
|
|
118
|
+
return viem.bytesToHex(addressBytes);
|
|
119
|
+
}// concurrent
|
|
120
|
+
function safePromiseAll(arr) {
|
|
121
|
+
// @ts-expect-error
|
|
122
|
+
if (!arr || !arr.length)
|
|
123
|
+
return Promise.resolve([]);
|
|
124
|
+
return Promise.all(arr);
|
|
125
|
+
}
|
|
126
|
+
// serial
|
|
127
|
+
function safePromiseLine(arr) {
|
|
128
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
129
|
+
var res, i, _a, _b;
|
|
130
|
+
return __generator(this, function (_c) {
|
|
131
|
+
switch (_c.label) {
|
|
132
|
+
case 0:
|
|
133
|
+
if (!arr || !arr.length)
|
|
134
|
+
return [2 /*return*/, []];
|
|
135
|
+
res = [];
|
|
136
|
+
i = 0;
|
|
137
|
+
_c.label = 1;
|
|
138
|
+
case 1:
|
|
139
|
+
if (!(i < arr.length)) return [3 /*break*/, 6];
|
|
140
|
+
_c.label = 2;
|
|
141
|
+
case 2:
|
|
142
|
+
_c.trys.push([2, 4, , 5]);
|
|
143
|
+
_b = (_a = res).push;
|
|
144
|
+
return [4 /*yield*/, arr[i](i)];
|
|
145
|
+
case 3:
|
|
146
|
+
_b.apply(_a, [_c.sent()]);
|
|
147
|
+
return [3 /*break*/, 5];
|
|
148
|
+
case 4:
|
|
149
|
+
_c.sent();
|
|
150
|
+
return [3 /*break*/, 5];
|
|
151
|
+
case 5:
|
|
152
|
+
i++;
|
|
153
|
+
return [3 /*break*/, 1];
|
|
154
|
+
case 6: return [2 /*return*/, res];
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
}function _typeof(ele) {
|
|
159
|
+
if (typeof ele !== 'object')
|
|
160
|
+
return (typeof ele).toLowerCase();
|
|
161
|
+
var typeStr = Object.prototype.toString.call(ele);
|
|
162
|
+
return typeStr.slice(8, typeStr.length - 1).toLowerCase();
|
|
163
|
+
}/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
|
|
164
|
+
/**
|
|
165
|
+
* 4KB JS implementation of secp256k1 ECDSA / Schnorr signatures & ECDH.
|
|
166
|
+
* Compliant with RFC6979 & BIP340.
|
|
167
|
+
* @module
|
|
168
|
+
*/
|
|
169
|
+
/**
|
|
170
|
+
* Curve params. secp256k1 is short weierstrass / koblitz curve. Equation is y² == x³ + ax + b.
|
|
171
|
+
* * P = `2n**256n-2n**32n-2n**977n` // field over which calculations are done
|
|
172
|
+
* * N = `2n**256n - 0x14551231950b75fc4402da1732fc9bebfn` // group order, amount of curve points
|
|
173
|
+
* * h = `1n` // cofactor
|
|
174
|
+
* * a = `0n` // equation param
|
|
175
|
+
* * b = `7n` // equation param
|
|
176
|
+
* * Gx, Gy are coordinates of Generator / base point
|
|
177
|
+
*/
|
|
178
|
+
const secp256k1_CURVE = {
|
|
179
|
+
p: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,
|
|
180
|
+
n: 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,
|
|
181
|
+
b: 7n,
|
|
182
|
+
Gx: 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,
|
|
183
|
+
Gy: 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,
|
|
184
|
+
};
|
|
185
|
+
const { p: P, n: N, Gx, Gy, b: _b } = secp256k1_CURVE;
|
|
186
|
+
const L = 32; // field / group byte length
|
|
187
|
+
const L2 = 64;
|
|
188
|
+
// Helpers and Precomputes sections are reused between libraries
|
|
189
|
+
// ## Helpers
|
|
190
|
+
// ----------
|
|
191
|
+
// error helper, messes-up stack trace
|
|
192
|
+
const err = (m = '') => {
|
|
193
|
+
throw new Error(m);
|
|
194
|
+
};
|
|
195
|
+
const isBig = (n) => typeof n === 'bigint'; // is big integer
|
|
196
|
+
const isStr = (s) => typeof s === 'string'; // is string
|
|
197
|
+
const isBytes = (a) => a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
|
|
198
|
+
/** assert is Uint8Array (of specific length) */
|
|
199
|
+
const abytes = (a, l) => !isBytes(a) || (typeof l === 'number' && l > 0 && a.length !== l)
|
|
200
|
+
? err('Uint8Array expected')
|
|
201
|
+
: a;
|
|
202
|
+
/** create Uint8Array */
|
|
203
|
+
const u8n = (len) => new Uint8Array(len);
|
|
204
|
+
const u8fr = (buf) => Uint8Array.from(buf);
|
|
205
|
+
const padh = (n, pad) => n.toString(16).padStart(pad, '0');
|
|
206
|
+
const bytesToHex = (b) => Array.from(abytes(b))
|
|
207
|
+
.map((e) => padh(e, 2))
|
|
208
|
+
.join('');
|
|
209
|
+
const C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; // ASCII characters
|
|
210
|
+
const _ch = (ch) => {
|
|
211
|
+
if (ch >= C._0 && ch <= C._9)
|
|
212
|
+
return ch - C._0; // '2' => 50-48
|
|
213
|
+
if (ch >= C.A && ch <= C.F)
|
|
214
|
+
return ch - (C.A - 10); // 'B' => 66-(65-10)
|
|
215
|
+
if (ch >= C.a && ch <= C.f)
|
|
216
|
+
return ch - (C.a - 10); // 'b' => 98-(97-10)
|
|
217
|
+
return;
|
|
218
|
+
};
|
|
219
|
+
const hexToBytes = (hex) => {
|
|
220
|
+
const e = 'hex invalid';
|
|
221
|
+
if (!isStr(hex))
|
|
222
|
+
return err(e);
|
|
223
|
+
const hl = hex.length;
|
|
224
|
+
const al = hl / 2;
|
|
225
|
+
if (hl % 2)
|
|
226
|
+
return err(e);
|
|
227
|
+
const array = u8n(al);
|
|
228
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
229
|
+
// treat each char as ASCII
|
|
230
|
+
const n1 = _ch(hex.charCodeAt(hi)); // parse first char, multiply it by 16
|
|
231
|
+
const n2 = _ch(hex.charCodeAt(hi + 1)); // parse second char
|
|
232
|
+
if (n1 === undefined || n2 === undefined)
|
|
233
|
+
return err(e);
|
|
234
|
+
array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9
|
|
235
|
+
}
|
|
236
|
+
return array;
|
|
237
|
+
};
|
|
238
|
+
/** normalize hex or ui8a to ui8a */
|
|
239
|
+
const toU8 = (a, len) => abytes(isStr(a) ? hexToBytes(a) : u8fr(abytes(a)), len);
|
|
240
|
+
const cr = () => globalThis?.crypto; // WebCrypto is available in all modern environments
|
|
241
|
+
const subtle = () => cr()?.subtle ?? err('crypto.subtle must be defined');
|
|
242
|
+
// prettier-ignore
|
|
243
|
+
const concatBytes = (...arrs) => {
|
|
244
|
+
const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0)); // create u8a of summed length
|
|
245
|
+
let pad = 0; // walk through each array,
|
|
246
|
+
arrs.forEach(a => { r.set(a, pad); pad += a.length; }); // ensure they have proper type
|
|
247
|
+
return r;
|
|
248
|
+
};
|
|
249
|
+
/** WebCrypto OS-level CSPRNG (random number generator). Will throw when not available. */
|
|
250
|
+
const randomBytes = (len = L) => {
|
|
251
|
+
const c = cr();
|
|
252
|
+
return c.getRandomValues(u8n(len));
|
|
253
|
+
};
|
|
254
|
+
const big = BigInt;
|
|
255
|
+
const arange = (n, min, max, msg = 'bad number: out of range') => isBig(n) && min <= n && n < max ? n : err(msg);
|
|
256
|
+
/** modular division */
|
|
257
|
+
const M = (a, b = P) => {
|
|
258
|
+
const r = a % b;
|
|
259
|
+
return r >= 0n ? r : b + r;
|
|
260
|
+
};
|
|
261
|
+
const modN = (a) => M(a, N);
|
|
262
|
+
/** Modular inversion using eucledian GCD (non-CT). No negative exponent for now. */
|
|
263
|
+
// prettier-ignore
|
|
264
|
+
const invert = (num, md) => {
|
|
265
|
+
if (num === 0n || md <= 0n)
|
|
266
|
+
err('no inverse n=' + num + ' mod=' + md);
|
|
267
|
+
let a = M(num, md), b = md, x = 0n, u = 1n;
|
|
268
|
+
while (a !== 0n) {
|
|
269
|
+
const q = b / a, r = b % a;
|
|
270
|
+
const m = x - u * q;
|
|
271
|
+
b = a, a = r, x = u, u = m;
|
|
272
|
+
}
|
|
273
|
+
return b === 1n ? M(x, md) : err('no inverse'); // b is gcd at this point
|
|
274
|
+
};
|
|
275
|
+
const apoint = (p) => (p instanceof Point ? p : err('Point expected'));
|
|
276
|
+
// ## End of Helpers
|
|
277
|
+
// -----------------
|
|
278
|
+
/** secp256k1 formula. Koblitz curves are subclass of weierstrass curves with a=0, making it x³+b */
|
|
279
|
+
const koblitz = (x) => M(M(x * x) * x + _b);
|
|
280
|
+
/** assert is field element or 0 */
|
|
281
|
+
const afield0 = (n) => arange(n, 0n, P);
|
|
282
|
+
/** assert is field element */
|
|
283
|
+
const afield = (n) => arange(n, 1n, P);
|
|
284
|
+
/** assert is group elem */
|
|
285
|
+
const agroup = (n) => arange(n, 1n, N);
|
|
286
|
+
const isEven = (y) => (y & 1n) === 0n;
|
|
287
|
+
/** create Uint8Array of byte n */
|
|
288
|
+
const u8of = (n) => Uint8Array.of(n);
|
|
289
|
+
const getPrefix = (y) => u8of(isEven(y) ? 0x02 : 0x03);
|
|
290
|
+
/** lift_x from BIP340 calculates square root. Validates x, then validates root*root. */
|
|
291
|
+
const lift_x = (x) => {
|
|
292
|
+
// Let c = x³ + 7 mod p. Fail if x ≥ p. (also fail if x < 1)
|
|
293
|
+
const c = koblitz(afield(x));
|
|
294
|
+
// c = √y
|
|
295
|
+
// y = c^((p+1)/4) mod p
|
|
296
|
+
// This formula works for fields p = 3 mod 4 -- a special, fast case.
|
|
297
|
+
// Paper: "Square Roots from 1;24,51,10 to Dan Shanks".
|
|
298
|
+
let r = 1n;
|
|
299
|
+
for (let num = c, e = (P + 1n) / 4n; e > 0n; e >>= 1n) {
|
|
300
|
+
// powMod: modular exponentiation.
|
|
301
|
+
if (e & 1n)
|
|
302
|
+
r = (r * num) % P; // Uses exponentiation by squaring.
|
|
303
|
+
num = (num * num) % P; // Not constant-time.
|
|
304
|
+
}
|
|
305
|
+
return M(r * r) === c ? r : err('sqrt invalid'); // check if result is valid
|
|
306
|
+
};
|
|
307
|
+
/** Point in 3d xyz projective coordinates. 3d takes less inversions than 2d. */
|
|
308
|
+
class Point {
|
|
309
|
+
static BASE;
|
|
310
|
+
static ZERO;
|
|
311
|
+
px;
|
|
312
|
+
py;
|
|
313
|
+
pz;
|
|
314
|
+
constructor(px, py, pz) {
|
|
315
|
+
this.px = afield0(px);
|
|
316
|
+
this.py = afield(py); // y can't be 0 in Projective
|
|
317
|
+
this.pz = afield0(pz);
|
|
318
|
+
Object.freeze(this);
|
|
319
|
+
}
|
|
320
|
+
/** Convert Uint8Array or hex string to Point. */
|
|
321
|
+
static fromBytes(bytes) {
|
|
322
|
+
abytes(bytes);
|
|
323
|
+
let p = undefined;
|
|
324
|
+
// First byte is prefix, rest is data. There are 2 kinds: compressed & uncompressed:
|
|
325
|
+
// * [0x02 or 0x03][32-byte x coordinate]
|
|
326
|
+
// * [0x04] [32-byte x coordinate][32-byte y coordinate]
|
|
327
|
+
const head = bytes[0];
|
|
328
|
+
const tail = bytes.subarray(1);
|
|
329
|
+
const x = sliceBytesNumBE(tail, 0, L);
|
|
330
|
+
const len = bytes.length;
|
|
331
|
+
// Compressed 33-byte point, 0x02 or 0x03 prefix
|
|
332
|
+
if (len === L + 1 && [0x02, 0x03].includes(head)) {
|
|
333
|
+
// Equation is y² == x³ + ax + b. We calculate y from x.
|
|
334
|
+
// y = √y²; there are two solutions: y, -y. Determine proper solution based on prefix
|
|
335
|
+
let y = lift_x(x);
|
|
336
|
+
const evenY = isEven(y);
|
|
337
|
+
const evenH = isEven(big(head));
|
|
338
|
+
if (evenH !== evenY)
|
|
339
|
+
y = M(-y);
|
|
340
|
+
p = new Point(x, y, 1n);
|
|
341
|
+
}
|
|
342
|
+
// Uncompressed 65-byte point, 0x04 prefix
|
|
343
|
+
if (len === L2 + 1 && head === 0x04)
|
|
344
|
+
p = new Point(x, sliceBytesNumBE(tail, L, L2), 1n);
|
|
345
|
+
// Validate point
|
|
346
|
+
return p ? p.assertValidity() : err('bad point: not on curve');
|
|
347
|
+
}
|
|
348
|
+
/** Equality check: compare points P&Q. */
|
|
349
|
+
equals(other) {
|
|
350
|
+
const { px: X1, py: Y1, pz: Z1 } = this;
|
|
351
|
+
const { px: X2, py: Y2, pz: Z2 } = apoint(other); // checks class equality
|
|
352
|
+
const X1Z2 = M(X1 * Z2);
|
|
353
|
+
const X2Z1 = M(X2 * Z1);
|
|
354
|
+
const Y1Z2 = M(Y1 * Z2);
|
|
355
|
+
const Y2Z1 = M(Y2 * Z1);
|
|
356
|
+
return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
|
|
357
|
+
}
|
|
358
|
+
is0() {
|
|
359
|
+
return this.equals(I);
|
|
360
|
+
}
|
|
361
|
+
/** Flip point over y coordinate. */
|
|
362
|
+
negate() {
|
|
363
|
+
return new Point(this.px, M(-this.py), this.pz);
|
|
364
|
+
}
|
|
365
|
+
/** Point doubling: P+P, complete formula. */
|
|
366
|
+
double() {
|
|
367
|
+
return this.add(this);
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Point addition: P+Q, complete, exception-free formula
|
|
371
|
+
* (Renes-Costello-Batina, algo 1 of [2015/1060](https://eprint.iacr.org/2015/1060)).
|
|
372
|
+
* Cost: `12M + 0S + 3*a + 3*b3 + 23add`.
|
|
373
|
+
*/
|
|
374
|
+
// prettier-ignore
|
|
375
|
+
add(other) {
|
|
376
|
+
const { px: X1, py: Y1, pz: Z1 } = this;
|
|
377
|
+
const { px: X2, py: Y2, pz: Z2 } = apoint(other);
|
|
378
|
+
const a = 0n;
|
|
379
|
+
const b = _b;
|
|
380
|
+
let X3 = 0n, Y3 = 0n, Z3 = 0n;
|
|
381
|
+
const b3 = M(b * 3n);
|
|
382
|
+
let t0 = M(X1 * X2), t1 = M(Y1 * Y2), t2 = M(Z1 * Z2), t3 = M(X1 + Y1); // step 1
|
|
383
|
+
let t4 = M(X2 + Y2); // step 5
|
|
384
|
+
t3 = M(t3 * t4);
|
|
385
|
+
t4 = M(t0 + t1);
|
|
386
|
+
t3 = M(t3 - t4);
|
|
387
|
+
t4 = M(X1 + Z1);
|
|
388
|
+
let t5 = M(X2 + Z2); // step 10
|
|
389
|
+
t4 = M(t4 * t5);
|
|
390
|
+
t5 = M(t0 + t2);
|
|
391
|
+
t4 = M(t4 - t5);
|
|
392
|
+
t5 = M(Y1 + Z1);
|
|
393
|
+
X3 = M(Y2 + Z2); // step 15
|
|
394
|
+
t5 = M(t5 * X3);
|
|
395
|
+
X3 = M(t1 + t2);
|
|
396
|
+
t5 = M(t5 - X3);
|
|
397
|
+
Z3 = M(a * t4);
|
|
398
|
+
X3 = M(b3 * t2); // step 20
|
|
399
|
+
Z3 = M(X3 + Z3);
|
|
400
|
+
X3 = M(t1 - Z3);
|
|
401
|
+
Z3 = M(t1 + Z3);
|
|
402
|
+
Y3 = M(X3 * Z3);
|
|
403
|
+
t1 = M(t0 + t0); // step 25
|
|
404
|
+
t1 = M(t1 + t0);
|
|
405
|
+
t2 = M(a * t2);
|
|
406
|
+
t4 = M(b3 * t4);
|
|
407
|
+
t1 = M(t1 + t2);
|
|
408
|
+
t2 = M(t0 - t2); // step 30
|
|
409
|
+
t2 = M(a * t2);
|
|
410
|
+
t4 = M(t4 + t2);
|
|
411
|
+
t0 = M(t1 * t4);
|
|
412
|
+
Y3 = M(Y3 + t0);
|
|
413
|
+
t0 = M(t5 * t4); // step 35
|
|
414
|
+
X3 = M(t3 * X3);
|
|
415
|
+
X3 = M(X3 - t0);
|
|
416
|
+
t0 = M(t3 * t1);
|
|
417
|
+
Z3 = M(t5 * Z3);
|
|
418
|
+
Z3 = M(Z3 + t0); // step 40
|
|
419
|
+
return new Point(X3, Y3, Z3);
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
|
|
423
|
+
* Uses {@link wNAF} for base point.
|
|
424
|
+
* Uses fake point to mitigate side-channel leakage.
|
|
425
|
+
* @param n scalar by which point is multiplied
|
|
426
|
+
* @param safe safe mode guards against timing attacks; unsafe mode is faster
|
|
427
|
+
*/
|
|
428
|
+
multiply(n, safe = true) {
|
|
429
|
+
if (!safe && n === 0n)
|
|
430
|
+
return I;
|
|
431
|
+
agroup(n);
|
|
432
|
+
if (n === 1n)
|
|
433
|
+
return this;
|
|
434
|
+
if (this.equals(G))
|
|
435
|
+
return wNAF(n).p;
|
|
436
|
+
// init result point & fake point
|
|
437
|
+
let p = I;
|
|
438
|
+
let f = G;
|
|
439
|
+
for (let d = this; n > 0n; d = d.double(), n >>= 1n) {
|
|
440
|
+
// if bit is present, add to point
|
|
441
|
+
// if not present, add to fake, for timing safety
|
|
442
|
+
if (n & 1n)
|
|
443
|
+
p = p.add(d);
|
|
444
|
+
else if (safe)
|
|
445
|
+
f = f.add(d);
|
|
446
|
+
}
|
|
447
|
+
return p;
|
|
448
|
+
}
|
|
449
|
+
/** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */
|
|
450
|
+
toAffine() {
|
|
451
|
+
const { px: x, py: y, pz: z } = this;
|
|
452
|
+
// fast-paths for ZERO point OR Z=1
|
|
453
|
+
if (this.equals(I))
|
|
454
|
+
return { x: 0n, y: 0n };
|
|
455
|
+
if (z === 1n)
|
|
456
|
+
return { x, y };
|
|
457
|
+
const iz = invert(z, P);
|
|
458
|
+
// (Z * Z^-1) must be 1, otherwise bad math
|
|
459
|
+
if (M(z * iz) !== 1n)
|
|
460
|
+
err('inverse invalid');
|
|
461
|
+
// x = X*Z^-1; y = Y*Z^-1
|
|
462
|
+
return { x: M(x * iz), y: M(y * iz) };
|
|
463
|
+
}
|
|
464
|
+
/** Checks if the point is valid and on-curve. */
|
|
465
|
+
assertValidity() {
|
|
466
|
+
const { x, y } = this.toAffine(); // convert to 2d xy affine point.
|
|
467
|
+
afield(x); // must be in range 1 <= x,y < P
|
|
468
|
+
afield(y);
|
|
469
|
+
// y² == x³ + ax + b, equation sides must be equal
|
|
470
|
+
return M(y * y) === koblitz(x) ? this : err('bad point: not on curve');
|
|
471
|
+
}
|
|
472
|
+
/** Converts point to 33/65-byte Uint8Array. */
|
|
473
|
+
toBytes(isCompressed = true) {
|
|
474
|
+
const { x, y } = this.assertValidity().toAffine();
|
|
475
|
+
const x32b = numTo32b(x);
|
|
476
|
+
if (isCompressed)
|
|
477
|
+
return concatBytes(getPrefix(y), x32b);
|
|
478
|
+
return concatBytes(u8of(0x04), x32b, numTo32b(y));
|
|
479
|
+
}
|
|
480
|
+
/** Create 3d xyz point from 2d xy. (0, 0) => (0, 1, 0), not (0, 0, 1) */
|
|
481
|
+
static fromAffine(ap) {
|
|
482
|
+
const { x, y } = ap;
|
|
483
|
+
return x === 0n && y === 0n ? I : new Point(x, y, 1n);
|
|
484
|
+
}
|
|
485
|
+
toHex(isCompressed) {
|
|
486
|
+
return bytesToHex(this.toBytes(isCompressed));
|
|
487
|
+
}
|
|
488
|
+
static fromPrivateKey(k) {
|
|
489
|
+
return G.multiply(toPrivScalar(k));
|
|
490
|
+
}
|
|
491
|
+
static fromHex(hex) {
|
|
492
|
+
return Point.fromBytes(toU8(hex));
|
|
493
|
+
}
|
|
494
|
+
get x() {
|
|
495
|
+
return this.toAffine().x;
|
|
496
|
+
}
|
|
497
|
+
get y() {
|
|
498
|
+
return this.toAffine().y;
|
|
499
|
+
}
|
|
500
|
+
toRawBytes(isCompressed) {
|
|
501
|
+
return this.toBytes(isCompressed);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
/** Generator / base point */
|
|
505
|
+
const G = new Point(Gx, Gy, 1n);
|
|
506
|
+
/** Identity / zero point */
|
|
507
|
+
const I = new Point(0n, 1n, 0n);
|
|
508
|
+
// Static aliases
|
|
509
|
+
Point.BASE = G;
|
|
510
|
+
Point.ZERO = I;
|
|
511
|
+
/** `Q = u1⋅G + u2⋅R`. Verifies Q is not ZERO. Unsafe: non-CT. */
|
|
512
|
+
const doubleScalarMulUns = (R, u1, u2) => {
|
|
513
|
+
return G.multiply(u1, false).add(R.multiply(u2, false)).assertValidity();
|
|
514
|
+
};
|
|
515
|
+
const bytesToNumBE = (b) => big('0x' + (bytesToHex(b) || '0'));
|
|
516
|
+
const sliceBytesNumBE = (b, from, to) => bytesToNumBE(b.subarray(from, to));
|
|
517
|
+
const B256 = 2n ** 256n; // secp256k1 is weierstrass curve. Equation is x³ + ax + b.
|
|
518
|
+
/** Number to 32b. Must be 0 <= num < B256. validate, pad, to bytes. */
|
|
519
|
+
const numTo32b = (num) => hexToBytes(padh(arange(num, 0n, B256), L2));
|
|
520
|
+
/** Normalize private key to scalar (bigint). Verifies scalar is in range 1<s<N */
|
|
521
|
+
const toPrivScalar = (pr) => {
|
|
522
|
+
const num = isBig(pr) ? pr : bytesToNumBE(toU8(pr, L));
|
|
523
|
+
return arange(num, 1n, N, 'private key invalid 3');
|
|
524
|
+
};
|
|
525
|
+
/** For Signature malleability, validates sig.s is bigger than N/2. */
|
|
526
|
+
const highS = (n) => n > N >> 1n;
|
|
527
|
+
/** ECDSA Signature class. Supports only compact 64-byte representation, not DER. */
|
|
528
|
+
class Signature {
|
|
529
|
+
r;
|
|
530
|
+
s;
|
|
531
|
+
recovery;
|
|
532
|
+
constructor(r, s, recovery) {
|
|
533
|
+
this.r = agroup(r); // 1 <= r < N
|
|
534
|
+
this.s = agroup(s); // 1 <= s < N
|
|
535
|
+
if (recovery != null)
|
|
536
|
+
this.recovery = recovery;
|
|
537
|
+
Object.freeze(this);
|
|
538
|
+
}
|
|
539
|
+
/** Create signature from 64b compact (r || s) representation. */
|
|
540
|
+
static fromBytes(b) {
|
|
541
|
+
abytes(b, L2);
|
|
542
|
+
const r = sliceBytesNumBE(b, 0, L);
|
|
543
|
+
const s = sliceBytesNumBE(b, L, L2);
|
|
544
|
+
return new Signature(r, s);
|
|
545
|
+
}
|
|
546
|
+
toBytes() {
|
|
547
|
+
const { r, s } = this;
|
|
548
|
+
return concatBytes(numTo32b(r), numTo32b(s));
|
|
549
|
+
}
|
|
550
|
+
/** Copy signature, with newly added recovery bit. */
|
|
551
|
+
addRecoveryBit(bit) {
|
|
552
|
+
return new Signature(this.r, this.s, bit);
|
|
553
|
+
}
|
|
554
|
+
hasHighS() {
|
|
555
|
+
return highS(this.s);
|
|
556
|
+
}
|
|
557
|
+
toCompactRawBytes() {
|
|
558
|
+
return this.toBytes();
|
|
559
|
+
}
|
|
560
|
+
toCompactHex() {
|
|
561
|
+
return bytesToHex(this.toBytes());
|
|
562
|
+
}
|
|
563
|
+
recoverPublicKey(msg) {
|
|
564
|
+
return recoverPublicKey(this, msg);
|
|
565
|
+
}
|
|
566
|
+
static fromCompact(hex) {
|
|
567
|
+
return Signature.fromBytes(toU8(hex, L2));
|
|
568
|
+
}
|
|
569
|
+
assertValidity() {
|
|
570
|
+
return this;
|
|
571
|
+
}
|
|
572
|
+
normalizeS() {
|
|
573
|
+
const { r, s, recovery } = this;
|
|
574
|
+
return highS(s) ? new Signature(r, modN(-s), recovery) : this;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* RFC6979: ensure ECDSA msg is X bytes, convert to BigInt.
|
|
579
|
+
* RFC suggests optional truncating via bits2octets.
|
|
580
|
+
* FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits,
|
|
581
|
+
* which matches bits2int. bits2int can produce res>N.
|
|
582
|
+
*/
|
|
583
|
+
const bits2int = (bytes) => {
|
|
584
|
+
const delta = bytes.length * 8 - 256;
|
|
585
|
+
if (delta > 1024)
|
|
586
|
+
err('msg invalid'); // our CUSTOM check, "just-in-case": prohibit long inputs
|
|
587
|
+
const num = bytesToNumBE(bytes);
|
|
588
|
+
return delta > 0 ? num >> big(delta) : num;
|
|
589
|
+
};
|
|
590
|
+
/** int2octets can't be used; pads small msgs with 0: BAD for truncation as per RFC vectors */
|
|
591
|
+
const bits2int_modN = (bytes) => modN(bits2int(abytes(bytes)));
|
|
592
|
+
const signOpts = { lowS: true };
|
|
593
|
+
// RFC6979 signature generation, preparation step.
|
|
594
|
+
const prepSig = (msgh, priv, opts = signOpts) => {
|
|
595
|
+
if (['der', 'recovered', 'canonical'].some((k) => k in opts))
|
|
596
|
+
// legacy opts
|
|
597
|
+
err('option not supported');
|
|
598
|
+
let { lowS, extraEntropy } = opts; // generates low-s sigs by default
|
|
599
|
+
if (lowS == null)
|
|
600
|
+
lowS = true; // RFC6979 3.2: we skip step A
|
|
601
|
+
const i2o = numTo32b; // int to octets
|
|
602
|
+
const h1i = bits2int_modN(toU8(msgh)); // msg bigint
|
|
603
|
+
const h1o = i2o(h1i); // msg octets
|
|
604
|
+
const d = toPrivScalar(priv); // validate private key, convert to bigint
|
|
605
|
+
const seed = [i2o(d), h1o]; // Step D of RFC6979 3.2
|
|
606
|
+
/** RFC6979 3.6: additional k' (optional). See {@link ExtraEntropy}. */
|
|
607
|
+
// K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
|
|
608
|
+
if (extraEntropy)
|
|
609
|
+
seed.push(extraEntropy === true ? randomBytes(L) : toU8(extraEntropy));
|
|
610
|
+
const m = h1i; // convert msg to bigint
|
|
611
|
+
// Converts signature params into point w r/s, checks result for validity.
|
|
612
|
+
// To transform k => Signature:
|
|
613
|
+
// q = k⋅G
|
|
614
|
+
// r = q.x mod n
|
|
615
|
+
// s = k^-1(m + rd) mod n
|
|
616
|
+
const k2sig = (kBytes) => {
|
|
617
|
+
// RFC 6979 Section 3.2, step 3: k = bits2int(T)
|
|
618
|
+
// Important: all mod() calls here must be done over N
|
|
619
|
+
const k = bits2int(kBytes);
|
|
620
|
+
if (!(1n <= k && k < N))
|
|
621
|
+
return; // Check 0 < k < CURVE.n
|
|
622
|
+
const q = G.multiply(k).toAffine(); // q = k⋅G
|
|
623
|
+
const r = modN(q.x); // r = q.x mod n
|
|
624
|
+
if (r === 0n)
|
|
625
|
+
return;
|
|
626
|
+
const ik = invert(k, N); // k^-1 mod n, NOT mod P
|
|
627
|
+
const s = modN(ik * modN(m + modN(d * r))); // s = k^-1(m + rd) mod n
|
|
628
|
+
if (s === 0n)
|
|
629
|
+
return;
|
|
630
|
+
let normS = s; // normalized S
|
|
631
|
+
let recovery = (q.x === r ? 0 : 2) | Number(q.y & 1n); // recovery bit (2 or 3, when q.x > n)
|
|
632
|
+
if (lowS && highS(s)) {
|
|
633
|
+
// if lowS was passed, ensure s is always
|
|
634
|
+
normS = modN(-s); // in the bottom half of CURVE.n
|
|
635
|
+
recovery ^= 1;
|
|
636
|
+
}
|
|
637
|
+
return new Signature(r, normS, recovery); // use normS, not s
|
|
638
|
+
};
|
|
639
|
+
return { seed: concatBytes(...seed), k2sig };
|
|
640
|
+
};
|
|
641
|
+
// HMAC-DRBG from NIST 800-90. Minimal, non-full-spec - used for RFC6979 signatures.
|
|
642
|
+
const hmacDrbg = (asynchronous) => {
|
|
643
|
+
let v = u8n(L); // Steps B, C of RFC6979 3.2: set hashLen
|
|
644
|
+
let k = u8n(L); // In our case, it's always equal to L
|
|
645
|
+
let i = 0; // Iterations counter, will throw when over max
|
|
646
|
+
const NULL = u8n(0);
|
|
647
|
+
const reset = () => {
|
|
648
|
+
v.fill(1);
|
|
649
|
+
k.fill(0);
|
|
650
|
+
i = 0;
|
|
651
|
+
};
|
|
652
|
+
const max = 1000;
|
|
653
|
+
const _e = 'drbg: tried 1000 values';
|
|
654
|
+
{
|
|
655
|
+
// asynchronous=true
|
|
656
|
+
// h = hmac(K || V || ...)
|
|
657
|
+
const h = (...b) => etc.hmacSha256Async(k, v, ...b);
|
|
658
|
+
const reseed = async (seed = NULL) => {
|
|
659
|
+
// HMAC-DRBG reseed() function. Steps D-G
|
|
660
|
+
k = await h(u8of(0x00), seed); // k = hmac(K || V || 0x00 || seed)
|
|
661
|
+
v = await h(); // v = hmac(K || V)
|
|
662
|
+
if (seed.length === 0)
|
|
663
|
+
return;
|
|
664
|
+
k = await h(u8of(0x01), seed); // k = hmac(K || V || 0x01 || seed)
|
|
665
|
+
v = await h(); // v = hmac(K || V)
|
|
666
|
+
};
|
|
667
|
+
// HMAC-DRBG generate() function
|
|
668
|
+
const gen = async () => {
|
|
669
|
+
if (i++ >= max)
|
|
670
|
+
err(_e);
|
|
671
|
+
v = await h(); // v = hmac(K || V)
|
|
672
|
+
return v; // this diverges from noble-curves: we don't allow arbitrary output len!
|
|
673
|
+
};
|
|
674
|
+
// Do not reuse returned fn for more than 1 sig:
|
|
675
|
+
// 1) it's slower (JIT screws up). 2. unsafe (async race conditions)
|
|
676
|
+
return async (seed, pred) => {
|
|
677
|
+
reset();
|
|
678
|
+
await reseed(seed); // Steps D-G
|
|
679
|
+
let res = undefined; // Step H: grind until k is in [1..n-1]
|
|
680
|
+
while (!(res = pred(await gen())))
|
|
681
|
+
await reseed(); // test predicate until it returns ok
|
|
682
|
+
reset();
|
|
683
|
+
return res;
|
|
684
|
+
};
|
|
685
|
+
}
|
|
686
|
+
};
|
|
687
|
+
/**
|
|
688
|
+
* Sign a msg hash using secp256k1. Async.
|
|
689
|
+
* Follows [SEC1](https://secg.org/sec1-v2.pdf) 4.1.2 & RFC6979.
|
|
690
|
+
* It's suggested to enable hedging ({@link ExtraEntropy}) to prevent fault attacks.
|
|
691
|
+
* @param msgh - message HASH, not message itself e.g. sha256(message)
|
|
692
|
+
* @param priv - private key
|
|
693
|
+
* @param opts - `lowS: true` prevents malleability, `extraEntropy: true` enables hedging
|
|
694
|
+
*/
|
|
695
|
+
const signAsync = async (msgh, priv, opts = signOpts) => {
|
|
696
|
+
// Re-run drbg until k2sig returns ok
|
|
697
|
+
const { seed, k2sig } = prepSig(msgh, priv, opts);
|
|
698
|
+
const sig = await hmacDrbg()(seed, k2sig);
|
|
699
|
+
return sig;
|
|
700
|
+
};
|
|
701
|
+
/**
|
|
702
|
+
* ECDSA public key recovery. Requires msg hash and recovery id.
|
|
703
|
+
* Follows [SEC1](https://secg.org/sec1-v2.pdf) 4.1.6.
|
|
704
|
+
*/
|
|
705
|
+
const recoverPublicKey = (sig, msgh) => {
|
|
706
|
+
const { r, s, recovery } = sig;
|
|
707
|
+
// 0 or 1 recovery id determines sign of "y" coordinate.
|
|
708
|
+
// 2 or 3 means q.x was >N.
|
|
709
|
+
if (![0, 1, 2, 3].includes(recovery))
|
|
710
|
+
err('recovery id invalid');
|
|
711
|
+
const h = bits2int_modN(toU8(msgh, L)); // Truncate hash
|
|
712
|
+
const radj = recovery === 2 || recovery === 3 ? r + N : r;
|
|
713
|
+
afield(radj); // ensure q.x is still a field element
|
|
714
|
+
const head = getPrefix(big(recovery)); // head is 0x02 or 0x03
|
|
715
|
+
const Rb = concatBytes(head, numTo32b(radj)); // concat head + r
|
|
716
|
+
const R = Point.fromBytes(Rb);
|
|
717
|
+
const ir = invert(radj, N); // r^-1
|
|
718
|
+
const u1 = modN(-h * ir); // -hr^-1
|
|
719
|
+
const u2 = modN(s * ir); // sr^-1
|
|
720
|
+
return doubleScalarMulUns(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)
|
|
721
|
+
};
|
|
722
|
+
// FIPS 186 B.4.1 compliant key generation produces private keys with modulo bias being neglible.
|
|
723
|
+
// takes >N+8 bytes, returns (hash mod n-1)+1
|
|
724
|
+
const hashToPrivateKey = (hash) => {
|
|
725
|
+
hash = toU8(hash);
|
|
726
|
+
if (hash.length < L + 8 || hash.length > 1024)
|
|
727
|
+
err('expected 40-1024b');
|
|
728
|
+
const num = M(bytesToNumBE(hash), N - 1n);
|
|
729
|
+
return numTo32b(num + 1n);
|
|
730
|
+
};
|
|
731
|
+
const _sha = 'SHA-256';
|
|
732
|
+
/** Math, hex, byte helpers. Not in `utils` because utils share API with noble-curves. */
|
|
733
|
+
const etc = {
|
|
734
|
+
hexToBytes: hexToBytes,
|
|
735
|
+
bytesToHex: bytesToHex,
|
|
736
|
+
concatBytes: concatBytes,
|
|
737
|
+
bytesToNumberBE: bytesToNumBE,
|
|
738
|
+
numberToBytesBE: numTo32b,
|
|
739
|
+
mod: M,
|
|
740
|
+
invert: invert, // math utilities
|
|
741
|
+
hmacSha256Async: async (key, ...msgs) => {
|
|
742
|
+
const s = subtle();
|
|
743
|
+
const name = 'HMAC';
|
|
744
|
+
const k = await s.importKey('raw', key, { name, hash: { name: _sha } }, false, ['sign']);
|
|
745
|
+
return u8n(await s.sign(name, k, concatBytes(...msgs)));
|
|
746
|
+
},
|
|
747
|
+
hmacSha256Sync: undefined, // For TypeScript. Actual logic is below
|
|
748
|
+
hashToPrivateKey: hashToPrivateKey,
|
|
749
|
+
randomBytes: randomBytes,
|
|
750
|
+
};
|
|
751
|
+
// ## Precomputes
|
|
752
|
+
// --------------
|
|
753
|
+
const W = 8; // W is window size
|
|
754
|
+
const scalarBits = 256;
|
|
755
|
+
const pwindows = Math.ceil(scalarBits / W) + 1; // 33 for W=8
|
|
756
|
+
const pwindowSize = 2 ** (W - 1); // 128 for W=8
|
|
757
|
+
const precompute = () => {
|
|
758
|
+
const points = [];
|
|
759
|
+
let p = G;
|
|
760
|
+
let b = p;
|
|
761
|
+
for (let w = 0; w < pwindows; w++) {
|
|
762
|
+
b = p;
|
|
763
|
+
points.push(b);
|
|
764
|
+
for (let i = 1; i < pwindowSize; i++) {
|
|
765
|
+
b = b.add(p);
|
|
766
|
+
points.push(b);
|
|
767
|
+
} // i=1, bc we skip 0
|
|
768
|
+
p = b.double();
|
|
769
|
+
}
|
|
770
|
+
return points;
|
|
771
|
+
};
|
|
772
|
+
let Gpows = undefined; // precomputes for base point G
|
|
773
|
+
// const-time negate
|
|
774
|
+
const ctneg = (cnd, p) => {
|
|
775
|
+
const n = p.negate();
|
|
776
|
+
return cnd ? n : p;
|
|
777
|
+
};
|
|
778
|
+
/**
|
|
779
|
+
* Precomputes give 12x faster getPublicKey(), 10x sign(), 2x verify() by
|
|
780
|
+
* caching multiples of G (base point). Cache is stored in 32MB of RAM.
|
|
781
|
+
* Any time `G.multiply` is done, precomputes are used.
|
|
782
|
+
* Not used for getSharedSecret, which instead multiplies random pubkey `P.multiply`.
|
|
783
|
+
*
|
|
784
|
+
* w-ary non-adjacent form (wNAF) precomputation method is 10% slower than windowed method,
|
|
785
|
+
* but takes 2x less RAM. RAM reduction is possible by utilizing `.subtract`.
|
|
786
|
+
*
|
|
787
|
+
* !! Precomputes can be disabled by commenting-out call of the wNAF() inside Point#multiply().
|
|
788
|
+
*/
|
|
789
|
+
const wNAF = (n) => {
|
|
790
|
+
const comp = Gpows || (Gpows = precompute());
|
|
791
|
+
let p = I;
|
|
792
|
+
let f = G; // f must be G, or could become I in the end
|
|
793
|
+
const pow_2_w = 2 ** W; // 256 for W=8
|
|
794
|
+
const maxNum = pow_2_w; // 256 for W=8
|
|
795
|
+
const mask = big(pow_2_w - 1); // 255 for W=8 == mask 0b11111111
|
|
796
|
+
const shiftBy = big(W); // 8 for W=8
|
|
797
|
+
for (let w = 0; w < pwindows; w++) {
|
|
798
|
+
let wbits = Number(n & mask); // extract W bits.
|
|
799
|
+
n >>= shiftBy; // shift number by W bits.
|
|
800
|
+
if (wbits > pwindowSize) {
|
|
801
|
+
wbits -= maxNum;
|
|
802
|
+
n += 1n;
|
|
803
|
+
} // split if bits > max: +224 => 256-32
|
|
804
|
+
const off = w * pwindowSize;
|
|
805
|
+
const offF = off; // offsets, evaluate both
|
|
806
|
+
const offP = off + Math.abs(wbits) - 1;
|
|
807
|
+
const isEven = w % 2 !== 0; // conditions, evaluate both
|
|
808
|
+
const isNeg = wbits < 0;
|
|
809
|
+
if (wbits === 0) {
|
|
810
|
+
// off == I: can't add it. Adding random offF instead.
|
|
811
|
+
f = f.add(ctneg(isEven, comp[offF])); // bits are 0: add garbage to fake point
|
|
812
|
+
}
|
|
813
|
+
else {
|
|
814
|
+
p = p.add(ctneg(isNeg, comp[offP])); // bits are 1: add to result point
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
return { p, f }; // return both real and fake points for JIT
|
|
818
|
+
};/**
|
|
819
|
+
* RLP encode a payload into a digest
|
|
820
|
+
* @param payload Payload to encode
|
|
821
|
+
* @returns RLP encoded payload
|
|
822
|
+
*/
|
|
823
|
+
function encodePayload(payload) {
|
|
824
|
+
if (_typeof(payload) === 'array') {
|
|
825
|
+
var formatted = payload.map(function (v) {
|
|
826
|
+
if (_typeof(v) === 'string') {
|
|
827
|
+
if (/^0x[0-9a-fA-F]+$/.test(v)) {
|
|
828
|
+
// hex-encoded data → raw bytes
|
|
829
|
+
return viem.hexToBytes(v);
|
|
830
|
+
}
|
|
831
|
+
else if (!isNaN(+v)) {
|
|
832
|
+
// number-like string → hex → bytes
|
|
833
|
+
return v === '0' ? new Uint8Array([]) : viem.hexToBytes(viem.numberToHex(+v));
|
|
834
|
+
}
|
|
835
|
+
else {
|
|
836
|
+
// plain string → UTF-8 bytes
|
|
837
|
+
return new TextEncoder().encode(v);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
else if (_typeof(v) === 'number' || _typeof(v) === 'bigint') {
|
|
841
|
+
// produce minimal hex, then arrayify
|
|
842
|
+
return v === 0 || v === BigInt(0) ? new Uint8Array([]) : viem.hexToBytes(viem.numberToHex(v));
|
|
843
|
+
}
|
|
844
|
+
else if (_typeof(v) === 'boolean') {
|
|
845
|
+
return v ? Uint8Array.from([1]) : new Uint8Array([]);
|
|
846
|
+
}
|
|
847
|
+
else {
|
|
848
|
+
return v;
|
|
849
|
+
}
|
|
850
|
+
});
|
|
851
|
+
return rlp.encode(formatted);
|
|
852
|
+
}
|
|
853
|
+
if (_typeof(payload) === 'boolean') {
|
|
854
|
+
return rlp.encode(payload ? Uint8Array.from([1]) : new Uint8Array([]));
|
|
855
|
+
}
|
|
856
|
+
return rlp.encode(payload);
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* Sign a message using the provided private key
|
|
860
|
+
* @param payload Payload to sign
|
|
861
|
+
* @param privateKey Private key to sign with
|
|
862
|
+
* @returns Signature object with r, s, v components
|
|
863
|
+
*/
|
|
864
|
+
function signMessage(payload, privateKey) {
|
|
865
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
866
|
+
var encoded, digestHex, digest, privateKeyBytes, signature, compact, rBytes, sBytes;
|
|
867
|
+
return __generator(this, function (_a) {
|
|
868
|
+
switch (_a.label) {
|
|
869
|
+
case 0:
|
|
870
|
+
encoded = encodePayload(payload);
|
|
871
|
+
digestHex = viem.keccak256(encoded);
|
|
872
|
+
digest = viem.hexToBytes(digestHex);
|
|
873
|
+
privateKeyBytes = viem.hexToBytes(privateKey);
|
|
874
|
+
return [4 /*yield*/, signAsync(digest, privateKeyBytes, { lowS: true })];
|
|
875
|
+
case 1:
|
|
876
|
+
signature = _a.sent();
|
|
877
|
+
compact = signature.toCompactRawBytes();
|
|
878
|
+
rBytes = compact.subarray(0, 32);
|
|
879
|
+
sBytes = compact.subarray(32, 64);
|
|
880
|
+
return [2 /*return*/, {
|
|
881
|
+
r: viem.bytesToHex(rBytes),
|
|
882
|
+
s: viem.bytesToHex(sBytes),
|
|
883
|
+
v: signature.recovery,
|
|
884
|
+
}];
|
|
885
|
+
}
|
|
886
|
+
});
|
|
887
|
+
});
|
|
888
|
+
}
|
|
889
|
+
function toHex(value) {
|
|
890
|
+
var type = _typeof(value);
|
|
891
|
+
try {
|
|
892
|
+
switch (type) {
|
|
893
|
+
case 'boolean':
|
|
894
|
+
return viem.boolToHex(value);
|
|
895
|
+
case 'number':
|
|
896
|
+
case 'bigint':
|
|
897
|
+
return viem.numberToHex(value);
|
|
898
|
+
case 'string':
|
|
899
|
+
if (!isNaN(+value))
|
|
900
|
+
return viem.numberToHex(+value);
|
|
901
|
+
return viem.stringToHex(value);
|
|
902
|
+
case 'uint8array':
|
|
903
|
+
case 'uint16array':
|
|
904
|
+
case 'uint32array':
|
|
905
|
+
case 'int8array':
|
|
906
|
+
case 'int16array':
|
|
907
|
+
case 'int32array':
|
|
908
|
+
case 'arraybuffer':
|
|
909
|
+
return viem.bytesToHex(value);
|
|
910
|
+
case 'array':
|
|
911
|
+
if (value.length === 0)
|
|
912
|
+
return '0x';
|
|
913
|
+
else if (value.every(function (item) { return typeof item === 'number'; }))
|
|
914
|
+
return viem.bytesToHex(Uint8Array.from(value));
|
|
915
|
+
else
|
|
916
|
+
return viem.bytesToHex(viem.stringToBytes(JSON.stringify(value)));
|
|
917
|
+
default:
|
|
918
|
+
return viem.bytesToHex(viem.stringToBytes(JSON.stringify(value)));
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
catch (e) {
|
|
922
|
+
console.error('[1Money toHex]: ', e);
|
|
923
|
+
return '0x';
|
|
924
|
+
}
|
|
925
|
+
}function encodeRlpListHeader(length) {
|
|
926
|
+
if (length < 56) {
|
|
927
|
+
// Short list: single byte prefix
|
|
928
|
+
return Uint8Array.from([0xc0 + length]);
|
|
929
|
+
}
|
|
930
|
+
else {
|
|
931
|
+
// Long list: prefix 0xf7 + length of length + actual length bytes
|
|
932
|
+
var lenBytes = [];
|
|
933
|
+
var temp = length;
|
|
934
|
+
while (temp > 0) {
|
|
935
|
+
lenBytes.unshift(temp & 0xff);
|
|
936
|
+
temp >>= 8;
|
|
937
|
+
}
|
|
938
|
+
return Uint8Array.from(__spreadArray([0xf7 + lenBytes.length], lenBytes, true));
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
function calcTxHash(payload, signature) {
|
|
942
|
+
var pEncode = encodePayload(payload);
|
|
943
|
+
var vEncode = rlp.encode(typeof signature.v === 'boolean'
|
|
944
|
+
? signature.v
|
|
945
|
+
? Uint8Array.from([1])
|
|
946
|
+
: new Uint8Array([])
|
|
947
|
+
: BigInt(signature.v));
|
|
948
|
+
var rEncode = rlp.encode(viem.hexToBytes(signature.r));
|
|
949
|
+
var sEncode = rlp.encode(viem.hexToBytes(signature.s));
|
|
950
|
+
var vrsBytes = new Uint8Array(vEncode.length + rEncode.length + sEncode.length);
|
|
951
|
+
vrsBytes.set(vEncode, 0);
|
|
952
|
+
vrsBytes.set(rEncode, vEncode.length);
|
|
953
|
+
vrsBytes.set(sEncode, vEncode.length + rEncode.length);
|
|
954
|
+
var header = encodeRlpListHeader(pEncode.length + vrsBytes.length);
|
|
955
|
+
var encoded = new Uint8Array(header.length + pEncode.length + vrsBytes.length);
|
|
956
|
+
encoded.set(header, 0);
|
|
957
|
+
encoded.set(pEncode, header.length);
|
|
958
|
+
encoded.set(vrsBytes, header.length + pEncode.length);
|
|
959
|
+
return viem.keccak256(encoded);
|
|
960
|
+
}var ResponsePromise = /** @class */ (function () {
|
|
961
|
+
function ResponsePromise() {
|
|
962
|
+
var _this = this;
|
|
963
|
+
this.promiseWrapper = new Promise(function (resolve, reject) {
|
|
964
|
+
_this._resolve = resolve;
|
|
965
|
+
_this._reject = reject;
|
|
966
|
+
});
|
|
967
|
+
this._restScope = ['success', 'failure', 'error', 'login', 'timeout'];
|
|
968
|
+
var _loop_1 = function (i) {
|
|
969
|
+
var method = this_1._restScope[i];
|
|
970
|
+
if (!method)
|
|
971
|
+
return "continue";
|
|
972
|
+
this_1.promiseWrapper[method] = function (_callback) {
|
|
973
|
+
// @ts-ignore
|
|
974
|
+
if (typeof _callback === 'function')
|
|
975
|
+
_this["_".concat(method)] = _callback;
|
|
976
|
+
var wrapper = _this.promiseWrapper;
|
|
977
|
+
delete wrapper[method];
|
|
978
|
+
var methods = _this._restScope.slice();
|
|
979
|
+
methods.splice(methods.indexOf(method), 1);
|
|
980
|
+
if (methods.every(function (_m) { return !!_m && !wrapper[_m]; }))
|
|
981
|
+
delete wrapper.rest;
|
|
982
|
+
return wrapper;
|
|
983
|
+
};
|
|
984
|
+
};
|
|
985
|
+
var this_1 = this;
|
|
986
|
+
for (var i = 0; i < this._restScope.length; i++) {
|
|
987
|
+
_loop_1(i);
|
|
988
|
+
}
|
|
989
|
+
this.promiseWrapper.rest = function (onRest, scope) {
|
|
990
|
+
// @ts-ignore
|
|
991
|
+
if (typeof onRest === 'function')
|
|
992
|
+
_this._rest = onRest;
|
|
993
|
+
var wrapper = _this.promiseWrapper;
|
|
994
|
+
delete wrapper.rest;
|
|
995
|
+
_this._restScope = scope || _this._restScope;
|
|
996
|
+
// @ts-ignore
|
|
997
|
+
if (_this._restScope.length === 0) {
|
|
998
|
+
console.warn('[1Money client]: The ".rest(cb, scope)" scope is empty and will never be triggered!');
|
|
999
|
+
}
|
|
1000
|
+
else {
|
|
1001
|
+
var deletedCounter_1 = 0;
|
|
1002
|
+
_this._restScope.forEach(function (method) {
|
|
1003
|
+
if (!method)
|
|
1004
|
+
return;
|
|
1005
|
+
if (wrapper[method]) {
|
|
1006
|
+
delete wrapper[method];
|
|
1007
|
+
}
|
|
1008
|
+
else {
|
|
1009
|
+
deletedCounter_1++;
|
|
1010
|
+
}
|
|
1011
|
+
});
|
|
1012
|
+
if (deletedCounter_1 === _this._restScope.length) {
|
|
1013
|
+
console.warn("[1Money client]: The \"".concat(_this._restScope.join(', '), "\" had been called and the \"rest\" will never be triggered!"));
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
return wrapper;
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
return ResponsePromise;
|
|
1020
|
+
}());
|
|
1021
|
+
var Request = /** @class */ (function () {
|
|
1022
|
+
function Request(config) {
|
|
1023
|
+
this._config = config || {};
|
|
1024
|
+
this.axios = axios$1;
|
|
1025
|
+
this.parseError = this.parseError.bind(this);
|
|
1026
|
+
this.setting = this.setting.bind(this);
|
|
1027
|
+
this.request = this.request.bind(this);
|
|
1028
|
+
}
|
|
1029
|
+
Request.prototype.parseError = function (err) {
|
|
1030
|
+
var _a, _b, _c, _d, _f, _g, _h, _j, _k;
|
|
1031
|
+
if (typeof err === 'string')
|
|
1032
|
+
err = new Error(err);
|
|
1033
|
+
// Ensure we have a valid error object
|
|
1034
|
+
if (!err || (_typeof(err) !== 'object' && _typeof(err) !== 'error')) {
|
|
1035
|
+
err = new Error('Unknown error occurred');
|
|
1036
|
+
}
|
|
1037
|
+
var name = (_a = err === null || err === void 0 ? void 0 : err.name) !== null && _a !== void 0 ? _a : 'Error';
|
|
1038
|
+
var message = (_d = (_b = err === null || err === void 0 ? void 0 : err.message) !== null && _b !== void 0 ? _b : (_c = err === null || err === void 0 ? void 0 : err.toString) === null || _c === void 0 ? void 0 : _c.call(err)) !== null && _d !== void 0 ? _d : 'Unknown error';
|
|
1039
|
+
var stack = (_f = err === null || err === void 0 ? void 0 : err.stack) !== null && _f !== void 0 ? _f : '';
|
|
1040
|
+
var status = (_h = (_g = err === null || err === void 0 ? void 0 : err.response) === null || _g === void 0 ? void 0 : _g.status) !== null && _h !== void 0 ? _h : 500;
|
|
1041
|
+
var data = (_k = (_j = err === null || err === void 0 ? void 0 : err.response) === null || _j === void 0 ? void 0 : _j.data) !== null && _k !== void 0 ? _k : undefined;
|
|
1042
|
+
// Validate status code
|
|
1043
|
+
if (typeof status !== 'number' || status < 100 || status > 599) {
|
|
1044
|
+
return {
|
|
1045
|
+
name: 'InvalidStatusError',
|
|
1046
|
+
message: 'Invalid HTTP status code',
|
|
1047
|
+
stack: stack,
|
|
1048
|
+
status: 500,
|
|
1049
|
+
data: data
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
return {
|
|
1053
|
+
name: name,
|
|
1054
|
+
message: message,
|
|
1055
|
+
stack: stack,
|
|
1056
|
+
status: status,
|
|
1057
|
+
data: data
|
|
1058
|
+
};
|
|
1059
|
+
};
|
|
1060
|
+
Request.prototype.setting = function (config) {
|
|
1061
|
+
if (!config)
|
|
1062
|
+
return console.warn('[1Money client]: setting method required correct parameters!');
|
|
1063
|
+
this._config = __assign(__assign({}, this._config), config);
|
|
1064
|
+
};
|
|
1065
|
+
Request.prototype.request = function (options) {
|
|
1066
|
+
var _this = this;
|
|
1067
|
+
// Set default security headers
|
|
1068
|
+
options.withCredentials = typeof options.withCredentials === 'boolean' ? options.withCredentials : true;
|
|
1069
|
+
options.headers = options.headers || {};
|
|
1070
|
+
options.headers['Accept'] = options.headers['Accept'] || '*/*';
|
|
1071
|
+
options.headers['X-Requested-With'] = options.headers['X-Requested-With'] || 'XMLHttpRequest';
|
|
1072
|
+
options.headers['X-Content-Type-Options'] = options.headers['X-Content-Type-Options'] || 'nosniff';
|
|
1073
|
+
var _a = this._config, initOnSuccess = _a.onSuccess, initOnFailure = _a.onFailure, initOnLogin = _a.onLogin, initOnError = _a.onError, initOnTimeout = _a.onTimeout, initIsSuccess = _a.isSuccess, initIsLogin = _a.isLogin, initTimeout = _a.timeout;
|
|
1074
|
+
var onSuccess = options.onSuccess, onFailure = options.onFailure, onLogin = options.onLogin, onError = options.onError, onTimeout = options.onTimeout, isSuccess = options.isSuccess, isLogin = options.isLogin, timeout = options.timeout;
|
|
1075
|
+
var rules = {
|
|
1076
|
+
success: isSuccess !== null && isSuccess !== void 0 ? isSuccess : initIsSuccess,
|
|
1077
|
+
login: isLogin !== null && isLogin !== void 0 ? isLogin : initIsLogin,
|
|
1078
|
+
};
|
|
1079
|
+
var ResPromise = new ResponsePromise();
|
|
1080
|
+
Promise.resolve().then(function () {
|
|
1081
|
+
var _a, _b, _c, _d, _f, _g, _h, _j, _k, _l, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
|
|
1082
|
+
var callbacks = {
|
|
1083
|
+
success: (_d = (_c = (_b = (_a = ResPromise._success) !== null && _a !== void 0 ? _a : (~ResPromise._restScope.indexOf('success') ? ResPromise._rest : undefined)) !== null && _b !== void 0 ? _b : onSuccess) !== null && _c !== void 0 ? _c : initOnSuccess) !== null && _d !== void 0 ? _d : (function (r, h) { return r; }),
|
|
1084
|
+
failure: (_j = (_h = (_g = (_f = ResPromise._failure) !== null && _f !== void 0 ? _f : (~ResPromise._restScope.indexOf('failure') ? ResPromise._rest : undefined)) !== null && _g !== void 0 ? _g : onFailure) !== null && _h !== void 0 ? _h : initOnFailure) !== null && _j !== void 0 ? _j : (function (v, h) { return v; }),
|
|
1085
|
+
error: (_p = (_o = (_l = (_k = ResPromise._error) !== null && _k !== void 0 ? _k : (~ResPromise._restScope.indexOf('error') ? ResPromise._rest : undefined)) !== null && _l !== void 0 ? _l : onError) !== null && _o !== void 0 ? _o : initOnError) !== null && _p !== void 0 ? _p : (function (v, h) { return v; }),
|
|
1086
|
+
login: (_t = (_s = (_r = (_q = ResPromise._login) !== null && _q !== void 0 ? _q : (~ResPromise._restScope.indexOf('login') ? ResPromise._rest : undefined)) !== null && _r !== void 0 ? _r : onLogin) !== null && _s !== void 0 ? _s : initOnLogin) !== null && _t !== void 0 ? _t : (function (v, h) { return v; }),
|
|
1087
|
+
timeout: (_x = (_w = (_v = (_u = ResPromise._timeout) !== null && _u !== void 0 ? _u : (~ResPromise._restScope.indexOf('timeout') ? ResPromise._rest : undefined)) !== null && _v !== void 0 ? _v : onTimeout) !== null && _w !== void 0 ? _w : initOnTimeout) !== null && _x !== void 0 ? _x : (function (v, h) { return v; }),
|
|
1088
|
+
};
|
|
1089
|
+
var existedHandler = {
|
|
1090
|
+
success: !!(ResPromise._success ||
|
|
1091
|
+
(ResPromise._rest && ~ResPromise._restScope.indexOf('success')) ||
|
|
1092
|
+
onSuccess ||
|
|
1093
|
+
initOnSuccess),
|
|
1094
|
+
failure: !!(ResPromise._failure ||
|
|
1095
|
+
(ResPromise._rest && ~ResPromise._restScope.indexOf('failure')) ||
|
|
1096
|
+
onFailure ||
|
|
1097
|
+
initOnFailure),
|
|
1098
|
+
login: !!(ResPromise._login ||
|
|
1099
|
+
(ResPromise._rest && ~ResPromise._restScope.indexOf('login')) ||
|
|
1100
|
+
onLogin ||
|
|
1101
|
+
initOnLogin),
|
|
1102
|
+
error: !!(ResPromise._error ||
|
|
1103
|
+
(ResPromise._rest && ~ResPromise._restScope.indexOf('error')) ||
|
|
1104
|
+
onError ||
|
|
1105
|
+
initOnError),
|
|
1106
|
+
timeout: !!(ResPromise._timeout ||
|
|
1107
|
+
(ResPromise._rest && ~ResPromise._restScope.indexOf('timeout')) ||
|
|
1108
|
+
onTimeout ||
|
|
1109
|
+
initOnTimeout),
|
|
1110
|
+
};
|
|
1111
|
+
var existedChainHandler = {
|
|
1112
|
+
success: !!(ResPromise._success ||
|
|
1113
|
+
(ResPromise._rest && ~ResPromise._restScope.indexOf('success'))),
|
|
1114
|
+
failure: !!(ResPromise._failure ||
|
|
1115
|
+
(ResPromise._rest && ~ResPromise._restScope.indexOf('failure'))),
|
|
1116
|
+
login: !!(ResPromise._login ||
|
|
1117
|
+
(ResPromise._rest && ~ResPromise._restScope.indexOf('login'))),
|
|
1118
|
+
error: !!(ResPromise._error ||
|
|
1119
|
+
(ResPromise._rest && ~ResPromise._restScope.indexOf('error'))),
|
|
1120
|
+
timeout: !!(ResPromise._timeout ||
|
|
1121
|
+
(ResPromise._rest && ~ResPromise._restScope.indexOf('timeout'))),
|
|
1122
|
+
};
|
|
1123
|
+
var errorHandler = function (e, headers) { return __awaiter(_this, void 0, void 0, function () {
|
|
1124
|
+
var err, result, _e_1;
|
|
1125
|
+
return __generator(this, function (_a) {
|
|
1126
|
+
switch (_a.label) {
|
|
1127
|
+
case 0:
|
|
1128
|
+
_a.trys.push([0, 2, , 3]);
|
|
1129
|
+
err = this.parseError(e);
|
|
1130
|
+
return [4 /*yield*/, Promise.resolve(callbacks.error(err, headers))];
|
|
1131
|
+
case 1:
|
|
1132
|
+
result = _a.sent();
|
|
1133
|
+
if (existedChainHandler.error)
|
|
1134
|
+
err = result;
|
|
1135
|
+
existedHandler.error ? ResPromise._resolve(err) : ResPromise._reject(err);
|
|
1136
|
+
return [3 /*break*/, 3];
|
|
1137
|
+
case 2:
|
|
1138
|
+
_e_1 = _a.sent();
|
|
1139
|
+
ResPromise._reject(this.parseError(_e_1));
|
|
1140
|
+
return [3 /*break*/, 3];
|
|
1141
|
+
case 3: return [2 /*return*/];
|
|
1142
|
+
}
|
|
1143
|
+
});
|
|
1144
|
+
}); };
|
|
1145
|
+
var timer = null;
|
|
1146
|
+
var isTimeout = false;
|
|
1147
|
+
var _timeout = timeout !== null && timeout !== void 0 ? timeout : initTimeout;
|
|
1148
|
+
// Cleanup function for timeout
|
|
1149
|
+
var cleanup = function () {
|
|
1150
|
+
if (timer !== null) {
|
|
1151
|
+
clearTimeout(timer);
|
|
1152
|
+
timer = null;
|
|
1153
|
+
}
|
|
1154
|
+
};
|
|
1155
|
+
if (_timeout) {
|
|
1156
|
+
timer = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
|
|
1157
|
+
var err, res, e_1;
|
|
1158
|
+
var _a, _b;
|
|
1159
|
+
return __generator(this, function (_c) {
|
|
1160
|
+
switch (_c.label) {
|
|
1161
|
+
case 0:
|
|
1162
|
+
_c.trys.push([0, 2, , 3]);
|
|
1163
|
+
isTimeout = true;
|
|
1164
|
+
cleanup();
|
|
1165
|
+
err = this.parseError('timeout');
|
|
1166
|
+
return [4 /*yield*/, Promise.resolve(callbacks.timeout(err, (_a = options.headers) !== null && _a !== void 0 ? _a : {}))];
|
|
1167
|
+
case 1:
|
|
1168
|
+
res = _c.sent();
|
|
1169
|
+
if (existedChainHandler.timeout)
|
|
1170
|
+
err = res;
|
|
1171
|
+
existedHandler.timeout ? ResPromise._resolve(err) : ResPromise._reject(err);
|
|
1172
|
+
return [3 /*break*/, 3];
|
|
1173
|
+
case 2:
|
|
1174
|
+
e_1 = _c.sent();
|
|
1175
|
+
errorHandler(e_1, (_b = options.headers) !== null && _b !== void 0 ? _b : {});
|
|
1176
|
+
return [3 /*break*/, 3];
|
|
1177
|
+
case 3: return [2 /*return*/];
|
|
1178
|
+
}
|
|
1179
|
+
});
|
|
1180
|
+
}); }, _timeout);
|
|
1181
|
+
}
|
|
1182
|
+
_this.axios(options).then(function (response) { return __awaiter(_this, void 0, void 0, function () {
|
|
1183
|
+
var status, data, headers, doSuccess, doLogin, res, result, result, result, e_2;
|
|
1184
|
+
var _a, _b;
|
|
1185
|
+
return __generator(this, function (_c) {
|
|
1186
|
+
switch (_c.label) {
|
|
1187
|
+
case 0:
|
|
1188
|
+
if (isTimeout)
|
|
1189
|
+
return [2 /*return*/];
|
|
1190
|
+
cleanup();
|
|
1191
|
+
status = response.status, data = response.data, headers = response.headers;
|
|
1192
|
+
_c.label = 1;
|
|
1193
|
+
case 1:
|
|
1194
|
+
_c.trys.push([1, 8, , 9]);
|
|
1195
|
+
doSuccess = (_a = rules.success) === null || _a === void 0 ? void 0 : _a.call(rules, data, status, headers);
|
|
1196
|
+
doLogin = (_b = rules.login) === null || _b === void 0 ? void 0 : _b.call(rules, data, status, headers);
|
|
1197
|
+
res = data;
|
|
1198
|
+
if (!doLogin) return [3 /*break*/, 3];
|
|
1199
|
+
return [4 /*yield*/, Promise.resolve(callbacks.login(data, headers))];
|
|
1200
|
+
case 2:
|
|
1201
|
+
result = _c.sent();
|
|
1202
|
+
if (existedChainHandler.login)
|
|
1203
|
+
res = result;
|
|
1204
|
+
return [3 /*break*/, 7];
|
|
1205
|
+
case 3:
|
|
1206
|
+
if (!doSuccess) return [3 /*break*/, 5];
|
|
1207
|
+
return [4 /*yield*/, Promise.resolve(callbacks.success(data, headers))];
|
|
1208
|
+
case 4:
|
|
1209
|
+
result = _c.sent();
|
|
1210
|
+
if (existedChainHandler.success)
|
|
1211
|
+
res = result;
|
|
1212
|
+
return [3 /*break*/, 7];
|
|
1213
|
+
case 5: return [4 /*yield*/, Promise.resolve(callbacks.failure(data, headers))];
|
|
1214
|
+
case 6:
|
|
1215
|
+
result = _c.sent();
|
|
1216
|
+
if (existedChainHandler.failure)
|
|
1217
|
+
res = result;
|
|
1218
|
+
_c.label = 7;
|
|
1219
|
+
case 7:
|
|
1220
|
+
ResPromise._resolve(res);
|
|
1221
|
+
return [3 /*break*/, 9];
|
|
1222
|
+
case 8:
|
|
1223
|
+
e_2 = _c.sent();
|
|
1224
|
+
errorHandler(e_2, headers);
|
|
1225
|
+
return [3 /*break*/, 9];
|
|
1226
|
+
case 9: return [2 /*return*/];
|
|
1227
|
+
}
|
|
1228
|
+
});
|
|
1229
|
+
}); }).catch(function (err) { return __awaiter(_this, void 0, void 0, function () {
|
|
1230
|
+
var status, data, headers, res, doLogin, e_3;
|
|
1231
|
+
var _a, _b, _c, _d, _f, _g, _h, _j, _k, _l, _o, _p, _q, _r, _s, _t, _u, _v;
|
|
1232
|
+
return __generator(this, function (_w) {
|
|
1233
|
+
switch (_w.label) {
|
|
1234
|
+
case 0:
|
|
1235
|
+
if (isTimeout)
|
|
1236
|
+
return [2 /*return*/];
|
|
1237
|
+
cleanup();
|
|
1238
|
+
console.error("[1Money client]: Error(".concat((_a = err.status) !== null && _a !== void 0 ? _a : 500, ", ").concat((_b = err.code) !== null && _b !== void 0 ? _b : 'UNKNOWN', "), Message: ").concat(err.message, ", Config: ").concat((_c = err.config) === null || _c === void 0 ? void 0 : _c.method, ", ").concat((_f = (_d = err.config) === null || _d === void 0 ? void 0 : _d.baseURL) !== null && _f !== void 0 ? _f : '').concat((_h = (_g = err.config) === null || _g === void 0 ? void 0 : _g.url) !== null && _h !== void 0 ? _h : '', ", ").concat(JSON.stringify((_k = (_j = err.config) === null || _j === void 0 ? void 0 : _j.headers) !== null && _k !== void 0 ? _k : {}), ", Request: ").concat(JSON.stringify((_o = (_l = err.config) === null || _l === void 0 ? void 0 : _l.data) !== null && _o !== void 0 ? _o : {}), ";"));
|
|
1239
|
+
status = (_q = (_p = err.response) === null || _p === void 0 ? void 0 : _p.status) !== null && _q !== void 0 ? _q : 500;
|
|
1240
|
+
data = (_s = (_r = err.response) === null || _r === void 0 ? void 0 : _r.data) !== null && _s !== void 0 ? _s : {};
|
|
1241
|
+
headers = (_u = (_t = err.response) === null || _t === void 0 ? void 0 : _t.headers) !== null && _u !== void 0 ? _u : {};
|
|
1242
|
+
_w.label = 1;
|
|
1243
|
+
case 1:
|
|
1244
|
+
_w.trys.push([1, 5, , 6]);
|
|
1245
|
+
res = data;
|
|
1246
|
+
doLogin = (_v = rules.login) === null || _v === void 0 ? void 0 : _v.call(rules, data, status, headers);
|
|
1247
|
+
if (!doLogin) return [3 /*break*/, 3];
|
|
1248
|
+
return [4 /*yield*/, Promise.resolve(callbacks.login(res, headers))];
|
|
1249
|
+
case 2:
|
|
1250
|
+
res = _w.sent();
|
|
1251
|
+
ResPromise._resolve(res);
|
|
1252
|
+
return [3 /*break*/, 4];
|
|
1253
|
+
case 3:
|
|
1254
|
+
errorHandler(err, headers);
|
|
1255
|
+
_w.label = 4;
|
|
1256
|
+
case 4: return [3 /*break*/, 6];
|
|
1257
|
+
case 5:
|
|
1258
|
+
e_3 = _w.sent();
|
|
1259
|
+
errorHandler(e_3, headers);
|
|
1260
|
+
return [3 /*break*/, 6];
|
|
1261
|
+
case 6: return [2 /*return*/];
|
|
1262
|
+
}
|
|
1263
|
+
});
|
|
1264
|
+
}); });
|
|
1265
|
+
});
|
|
1266
|
+
return ResPromise.promiseWrapper;
|
|
1267
|
+
};
|
|
1268
|
+
return Request;
|
|
1269
|
+
}());var _a = new Request({
|
|
1270
|
+
isSuccess: function (res, status) { return status === 200 && res.code == 0; },
|
|
1271
|
+
isLogin: function (res, status) { return status === 401 || res.code == 401; },
|
|
1272
|
+
timeout: 10000
|
|
1273
|
+
}), request = _a.request, setting = _a.setting, axios = _a.axios;
|
|
1274
|
+
function get(url, options) {
|
|
1275
|
+
return request(__assign(__assign({}, options), { method: 'get', url: url }));
|
|
1276
|
+
}
|
|
1277
|
+
function post(url, data, options) {
|
|
1278
|
+
return request(__assign(__assign({}, options), { method: 'post', url: url, data: data, headers: __assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers) }));
|
|
1279
|
+
}
|
|
1280
|
+
function postForm(url, data, options) {
|
|
1281
|
+
return request(__assign(__assign({}, options), { method: 'post', url: url, data: data, headers: __assign({ 'Content-Type': 'multipart/form-data' }, options === null || options === void 0 ? void 0 : options.headers) }));
|
|
1282
|
+
}
|
|
1283
|
+
function put(url, data, options) {
|
|
1284
|
+
return request(__assign(__assign({}, options), { method: 'put', url: url, data: data, headers: __assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers) }));
|
|
1285
|
+
}
|
|
1286
|
+
function patch(url, data, options) {
|
|
1287
|
+
return request(__assign(__assign({}, options), { method: 'patch', url: url, data: data, headers: __assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers) }));
|
|
1288
|
+
}
|
|
1289
|
+
function del(url, data, options) {
|
|
1290
|
+
return request(__assign(__assign({}, options), { method: 'delete', url: url, data: data, headers: __assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers) }));
|
|
1291
|
+
}
|
|
1292
|
+
function setInitConfig(config) {
|
|
1293
|
+
var baseURL = config.baseURL, rest = __rest(config, ["baseURL"]);
|
|
1294
|
+
axios.defaults.baseURL = baseURL || (typeof window !== 'undefined' ? location.origin : void 0);
|
|
1295
|
+
setting(rest);
|
|
1296
|
+
}
|
|
1297
|
+
var axiosStatic = axios;
|
|
1298
|
+
var client = {
|
|
1299
|
+
get: get,
|
|
1300
|
+
post: post,
|
|
1301
|
+
postForm: postForm,
|
|
1302
|
+
del: del,
|
|
1303
|
+
put: put,
|
|
1304
|
+
patch: patch,
|
|
1305
|
+
setInitConfig: setInitConfig,
|
|
1306
|
+
axiosStatic: axiosStatic
|
|
1307
|
+
};// Base URLs for the API
|
|
1308
|
+
var TESTNET_API_URL = 'https://api.testnet.1money.network';
|
|
1309
|
+
var MAINNET_API_URL = 'https://api.1money.network';
|
|
1310
|
+
var LOCAL_API_URL = 'http://localhost:18555';
|
|
1311
|
+
// API version
|
|
1312
|
+
var API_VERSION = 'v1';var API_PREFIX$5 = "/".concat(API_VERSION, "/accounts");
|
|
1313
|
+
/**
|
|
1314
|
+
* Accounts API methods
|
|
1315
|
+
*/
|
|
1316
|
+
var accountsApi = {
|
|
1317
|
+
/**
|
|
1318
|
+
* Get account nonce
|
|
1319
|
+
* @param address Address of the account to lookup nonce for
|
|
1320
|
+
* @returns Promise with account info response
|
|
1321
|
+
*/
|
|
1322
|
+
getNonce: function (address) {
|
|
1323
|
+
return get("".concat(API_PREFIX$5, "/nonce?address=").concat(address), { withCredentials: false });
|
|
1324
|
+
},
|
|
1325
|
+
/**
|
|
1326
|
+
* Get associated token account
|
|
1327
|
+
* @param address Address of the account to lookup associated token account for
|
|
1328
|
+
* @param token Token address to lookup associated token account for
|
|
1329
|
+
* @returns Promise with associated token account response
|
|
1330
|
+
*/
|
|
1331
|
+
getTokenAccount: function (address, token) {
|
|
1332
|
+
return get("".concat(API_PREFIX$5, "/token_account?address=").concat(address, "&token=").concat(token), { withCredentials: false });
|
|
1333
|
+
}
|
|
1334
|
+
};var API_PREFIX$4 = "/".concat(API_VERSION, "/checkpoints");
|
|
1335
|
+
/**
|
|
1336
|
+
* Checkpoint API methods
|
|
1337
|
+
*/
|
|
1338
|
+
var checkpointsApi = {
|
|
1339
|
+
/**
|
|
1340
|
+
* Get the current checkpoint number
|
|
1341
|
+
* @returns Promise with checkpoint number response
|
|
1342
|
+
*/
|
|
1343
|
+
getNumber: function () {
|
|
1344
|
+
return get("".concat(API_PREFIX$4, "/number"), { withCredentials: false });
|
|
1345
|
+
},
|
|
1346
|
+
/**
|
|
1347
|
+
* Get checkpoint by hash
|
|
1348
|
+
* @param hash Hash of the checkpoint to lookup
|
|
1349
|
+
* @param full Whether to include full transaction details
|
|
1350
|
+
* @returns Promise with checkpoint response
|
|
1351
|
+
*/
|
|
1352
|
+
getByHash: function (hash, full) {
|
|
1353
|
+
if (full === void 0) { full = false; }
|
|
1354
|
+
return get("".concat(API_PREFIX$4, "/by_hash?hash=").concat(hash, "&full=").concat(full), { withCredentials: false });
|
|
1355
|
+
},
|
|
1356
|
+
/**
|
|
1357
|
+
* Get checkpoint by number
|
|
1358
|
+
* @param number Number of the checkpoint to lookup
|
|
1359
|
+
* @param full Whether to include full transaction details
|
|
1360
|
+
* @returns Promise with checkpoint response
|
|
1361
|
+
*/
|
|
1362
|
+
getByNumber: function (number, full) {
|
|
1363
|
+
if (full === void 0) { full = false; }
|
|
1364
|
+
return get("".concat(API_PREFIX$4, "/by_number?number=").concat(number, "&full=").concat(full), { withCredentials: false });
|
|
1365
|
+
}
|
|
1366
|
+
};var API_PREFIX$3 = "/".concat(API_VERSION, "/tokens");
|
|
1367
|
+
/**
|
|
1368
|
+
* Tokens API methods
|
|
1369
|
+
*/
|
|
1370
|
+
var tokensApi = {
|
|
1371
|
+
/**
|
|
1372
|
+
* Get token metadata
|
|
1373
|
+
* @param token Token address to lookup metadata for
|
|
1374
|
+
* @returns Promise with token metadata response
|
|
1375
|
+
*/
|
|
1376
|
+
getTokenMetadata: function (token) {
|
|
1377
|
+
return get("".concat(API_PREFIX$3, "/token_metadata?token=").concat(token), { withCredentials: false });
|
|
1378
|
+
},
|
|
1379
|
+
/**
|
|
1380
|
+
* Manage token blacklist
|
|
1381
|
+
* @param payload Token blacklist request payload
|
|
1382
|
+
* @returns Promise with transaction hash response
|
|
1383
|
+
*/
|
|
1384
|
+
manageBlacklist: function (payload) {
|
|
1385
|
+
return post("".concat(API_PREFIX$3, "/manage_blacklist"), payload, { withCredentials: false });
|
|
1386
|
+
},
|
|
1387
|
+
/**
|
|
1388
|
+
* Manage token whitelist
|
|
1389
|
+
* @param payload Token whitelist request payload
|
|
1390
|
+
* @returns Promise with transaction hash response
|
|
1391
|
+
*/
|
|
1392
|
+
manageWhitelist: function (payload) {
|
|
1393
|
+
return post("".concat(API_PREFIX$3, "/manage_whitelist"), payload, { withCredentials: false });
|
|
1394
|
+
},
|
|
1395
|
+
/**
|
|
1396
|
+
* Burn tokens
|
|
1397
|
+
* @param payload Token burn request payload
|
|
1398
|
+
* @returns Promise with transaction hash response
|
|
1399
|
+
*/
|
|
1400
|
+
burnToken: function (payload) {
|
|
1401
|
+
return post("".concat(API_PREFIX$3, "/burn"), payload, { withCredentials: false });
|
|
1402
|
+
},
|
|
1403
|
+
/**
|
|
1404
|
+
* Grant or revoke token authority
|
|
1405
|
+
* @param payload Token authority request payload
|
|
1406
|
+
* @returns Promise with transaction hash response
|
|
1407
|
+
*/
|
|
1408
|
+
grantAuthority: function (payload) {
|
|
1409
|
+
return post("".concat(API_PREFIX$3, "/grant_authority"), payload, { withCredentials: false });
|
|
1410
|
+
},
|
|
1411
|
+
/**
|
|
1412
|
+
* Issue new token
|
|
1413
|
+
* @param payload Token issue request payload
|
|
1414
|
+
* @returns Promise with transaction hash and token address response
|
|
1415
|
+
*/
|
|
1416
|
+
issueToken: function (payload) {
|
|
1417
|
+
return post("".concat(API_PREFIX$3, "/issue"), payload, { withCredentials: false });
|
|
1418
|
+
},
|
|
1419
|
+
/**
|
|
1420
|
+
* Mint tokens
|
|
1421
|
+
* @param payload Token mint request payload
|
|
1422
|
+
* @returns Promise with transaction hash response
|
|
1423
|
+
*/
|
|
1424
|
+
mintToken: function (payload) {
|
|
1425
|
+
return post("".concat(API_PREFIX$3, "/mint"), payload, { withCredentials: false });
|
|
1426
|
+
},
|
|
1427
|
+
/**
|
|
1428
|
+
* Pause or unpause token
|
|
1429
|
+
* @param payload Token pause request payload
|
|
1430
|
+
* @returns Promise with transaction hash response
|
|
1431
|
+
*/
|
|
1432
|
+
pauseToken: function (payload) {
|
|
1433
|
+
return post("".concat(API_PREFIX$3, "/pause"), payload, { withCredentials: false });
|
|
1434
|
+
},
|
|
1435
|
+
/**
|
|
1436
|
+
* Update token metadata
|
|
1437
|
+
* @param payload Token metadata request payload
|
|
1438
|
+
* @returns Promise with transaction hash response
|
|
1439
|
+
*/
|
|
1440
|
+
updateMetadata: function (payload) {
|
|
1441
|
+
return post("".concat(API_PREFIX$3, "/update_metadata"), payload, { withCredentials: false });
|
|
1442
|
+
}
|
|
1443
|
+
};var API_PREFIX$2 = "/".concat(API_VERSION, "/transactions");
|
|
1444
|
+
/**
|
|
1445
|
+
* Transactions API methods
|
|
1446
|
+
*/
|
|
1447
|
+
var transactionsApi = {
|
|
1448
|
+
/**
|
|
1449
|
+
* Get transaction by hash
|
|
1450
|
+
* @param hash Hash of the transaction to lookup
|
|
1451
|
+
* @returns Promise with transaction response
|
|
1452
|
+
*/
|
|
1453
|
+
getByHash: function (hash) {
|
|
1454
|
+
return get("".concat(API_PREFIX$2, "/by_hash?hash=").concat(hash), { withCredentials: false });
|
|
1455
|
+
},
|
|
1456
|
+
/**
|
|
1457
|
+
* Get transaction receipt by hash
|
|
1458
|
+
* @param hash Hash of the transaction to lookup receipt for
|
|
1459
|
+
* @returns Promise with transaction receipt response
|
|
1460
|
+
*/
|
|
1461
|
+
getReceiptByHash: function (hash) {
|
|
1462
|
+
return get("".concat(API_PREFIX$2, "/receipt/by_hash?hash=").concat(hash), { withCredentials: false });
|
|
1463
|
+
},
|
|
1464
|
+
/**
|
|
1465
|
+
* Estimate transaction fee
|
|
1466
|
+
* @param from Address of the transaction author
|
|
1467
|
+
* @param value Value of the transaction
|
|
1468
|
+
* @param token Optional token address
|
|
1469
|
+
* @returns Promise with fee estimate response
|
|
1470
|
+
*/
|
|
1471
|
+
estimateFee: function (from, value, token) {
|
|
1472
|
+
var url = "".concat(API_PREFIX$2, "/estimate_fee?from=").concat(from, "&value=").concat(value);
|
|
1473
|
+
if (token) {
|
|
1474
|
+
url += "&token=".concat(token);
|
|
1475
|
+
}
|
|
1476
|
+
return get(url, { withCredentials: false });
|
|
1477
|
+
},
|
|
1478
|
+
/**
|
|
1479
|
+
* Submit payment transaction
|
|
1480
|
+
* @param payload Payment transaction payload
|
|
1481
|
+
* @returns Promise with transaction hash response
|
|
1482
|
+
*/
|
|
1483
|
+
payment: function (payload) {
|
|
1484
|
+
return post("".concat(API_PREFIX$2, "/payment"), payload, { withCredentials: false });
|
|
1485
|
+
}
|
|
1486
|
+
};var API_PREFIX$1 = "/".concat(API_VERSION, "/chains");
|
|
1487
|
+
/**
|
|
1488
|
+
* Checkpoint API methods
|
|
1489
|
+
*/
|
|
1490
|
+
var chainApi = {
|
|
1491
|
+
/**
|
|
1492
|
+
* Get the current chain id
|
|
1493
|
+
* @returns Promise with chain id response
|
|
1494
|
+
*/
|
|
1495
|
+
getChainId: function () {
|
|
1496
|
+
return get("".concat(API_PREFIX$1, "/chain_id"), { withCredentials: false });
|
|
1497
|
+
},
|
|
1498
|
+
};var API_PREFIX = "/".concat(API_VERSION, "/states");
|
|
1499
|
+
/**
|
|
1500
|
+
* State API methods
|
|
1501
|
+
*/
|
|
1502
|
+
var stateApi = {
|
|
1503
|
+
/**
|
|
1504
|
+
* Get latest epoch checkpoint
|
|
1505
|
+
* @returns Promise with latest epoch checkpoint response
|
|
1506
|
+
*/
|
|
1507
|
+
getLatestEpochCheckpoint: function () {
|
|
1508
|
+
return get("".concat(API_PREFIX, "/latest_epoch_checkpoint"), { withCredentials: false });
|
|
1509
|
+
}
|
|
1510
|
+
};// Authority types
|
|
1511
|
+
var AuthorityType;
|
|
1512
|
+
(function (AuthorityType) {
|
|
1513
|
+
AuthorityType["MasterMint"] = "MasterMint";
|
|
1514
|
+
AuthorityType["MintBurnTokens"] = "MintBurnTokens";
|
|
1515
|
+
AuthorityType["Pause"] = "Pause";
|
|
1516
|
+
AuthorityType["ManageList"] = "ManageList";
|
|
1517
|
+
AuthorityType["UpdateMetadata"] = "UpdateMetadata";
|
|
1518
|
+
})(AuthorityType || (AuthorityType = {}));
|
|
1519
|
+
var AuthorityAction;
|
|
1520
|
+
(function (AuthorityAction) {
|
|
1521
|
+
AuthorityAction["Grant"] = "Grant";
|
|
1522
|
+
AuthorityAction["Revoke"] = "Revoke";
|
|
1523
|
+
})(AuthorityAction || (AuthorityAction = {}));
|
|
1524
|
+
var ManageListAction;
|
|
1525
|
+
(function (ManageListAction) {
|
|
1526
|
+
ManageListAction["Add"] = "Add";
|
|
1527
|
+
ManageListAction["Remove"] = "Remove";
|
|
1528
|
+
})(ManageListAction || (ManageListAction = {}));
|
|
1529
|
+
var PauseAction;
|
|
1530
|
+
(function (PauseAction) {
|
|
1531
|
+
PauseAction["Pause"] = "Pause";
|
|
1532
|
+
PauseAction["Unpause"] = "Unpause";
|
|
1533
|
+
})(PauseAction || (PauseAction = {}));/**
|
|
1534
|
+
* API client for 1money network
|
|
1535
|
+
* @param options Configuration options
|
|
1536
|
+
* @param options.network Network to use (testnet, mainnet, local)
|
|
1537
|
+
* @param options.timeout Request timeout in milliseconds
|
|
1538
|
+
* @param options.chainId Custom chain ID (overrides the default for the selected network)
|
|
1539
|
+
*/
|
|
1540
|
+
function api(options) {
|
|
1541
|
+
var network = (options === null || options === void 0 ? void 0 : options.network) || 'mainnet';
|
|
1542
|
+
var baseURL = MAINNET_API_URL;
|
|
1543
|
+
// Set the base URL based on the network
|
|
1544
|
+
switch (network) {
|
|
1545
|
+
case 'mainnet':
|
|
1546
|
+
baseURL = MAINNET_API_URL;
|
|
1547
|
+
break;
|
|
1548
|
+
case 'testnet':
|
|
1549
|
+
baseURL = TESTNET_API_URL;
|
|
1550
|
+
break;
|
|
1551
|
+
case 'local':
|
|
1552
|
+
baseURL = LOCAL_API_URL;
|
|
1553
|
+
break;
|
|
1554
|
+
}
|
|
1555
|
+
// Initialize API configuration
|
|
1556
|
+
setInitConfig({
|
|
1557
|
+
baseURL: baseURL,
|
|
1558
|
+
// Treat status code 200 as success
|
|
1559
|
+
isSuccess: function (_res, status) { return status === 200; },
|
|
1560
|
+
timeout: (options === null || options === void 0 ? void 0 : options.timeout) || 10000
|
|
1561
|
+
});
|
|
1562
|
+
return {
|
|
1563
|
+
/**
|
|
1564
|
+
* Accounts API methods
|
|
1565
|
+
*/
|
|
1566
|
+
accounts: accountsApi,
|
|
1567
|
+
/**
|
|
1568
|
+
* Checkpoint API methods
|
|
1569
|
+
*/
|
|
1570
|
+
checkpoints: checkpointsApi,
|
|
1571
|
+
/**
|
|
1572
|
+
* Tokens API methods
|
|
1573
|
+
*/
|
|
1574
|
+
tokens: tokensApi,
|
|
1575
|
+
/**
|
|
1576
|
+
* Transactions API methods
|
|
1577
|
+
*/
|
|
1578
|
+
transactions: transactionsApi,
|
|
1579
|
+
/**
|
|
1580
|
+
* Chain API methods
|
|
1581
|
+
*/
|
|
1582
|
+
chain: chainApi,
|
|
1583
|
+
/**
|
|
1584
|
+
* State API methods
|
|
1585
|
+
*/
|
|
1586
|
+
state: stateApi,
|
|
1587
|
+
};
|
|
1588
|
+
}var index = {
|
|
1589
|
+
api: api,
|
|
1590
|
+
client: client,
|
|
1591
|
+
};exports._typeof=_typeof;exports.api=api;exports.calcTxHash=calcTxHash;exports.client=client;exports.default=index;exports.deriveTokenAddress=deriveTokenAddress;exports.encodePayload=encodePayload;exports.safePromiseAll=safePromiseAll;exports.safePromiseLine=safePromiseLine;exports.signMessage=signMessage;exports.toHex=toHex;
|