@descent-protocol/sdk
Version:
A Typescript library for interacting with the Descent Protocol
1,689 lines (1,677 loc) • 735 kB
JavaScript
var __defProp = Object.defineProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// node_modules/ethers/lib.esm/ethers.js
var ethers_exports = {};
__export(ethers_exports, {
AbiCoder: () => AbiCoder,
AbstractProvider: () => AbstractProvider,
AbstractSigner: () => AbstractSigner,
AlchemyProvider: () => AlchemyProvider,
AnkrProvider: () => AnkrProvider,
BaseContract: () => BaseContract,
BaseWallet: () => BaseWallet,
Block: () => Block,
BrowserProvider: () => BrowserProvider,
CloudflareProvider: () => CloudflareProvider,
ConstructorFragment: () => ConstructorFragment,
Contract: () => Contract,
ContractEventPayload: () => ContractEventPayload,
ContractFactory: () => ContractFactory,
ContractTransactionReceipt: () => ContractTransactionReceipt,
ContractTransactionResponse: () => ContractTransactionResponse,
ContractUnknownEventPayload: () => ContractUnknownEventPayload,
EnsPlugin: () => EnsPlugin,
EnsResolver: () => EnsResolver,
ErrorDescription: () => ErrorDescription,
ErrorFragment: () => ErrorFragment,
EtherSymbol: () => EtherSymbol,
EtherscanPlugin: () => EtherscanPlugin,
EtherscanProvider: () => EtherscanProvider,
EventFragment: () => EventFragment,
EventLog: () => EventLog,
EventPayload: () => EventPayload,
FallbackFragment: () => FallbackFragment,
FallbackProvider: () => FallbackProvider,
FeeData: () => FeeData,
FeeDataNetworkPlugin: () => FeeDataNetworkPlugin,
FetchCancelSignal: () => FetchCancelSignal,
FetchRequest: () => FetchRequest,
FetchResponse: () => FetchResponse,
FetchUrlFeeDataNetworkPlugin: () => FetchUrlFeeDataNetworkPlugin,
FixedNumber: () => FixedNumber,
Fragment: () => Fragment,
FunctionFragment: () => FunctionFragment,
GasCostPlugin: () => GasCostPlugin,
HDNodeVoidWallet: () => HDNodeVoidWallet,
HDNodeWallet: () => HDNodeWallet,
Indexed: () => Indexed,
InfuraProvider: () => InfuraProvider,
InfuraWebSocketProvider: () => InfuraWebSocketProvider,
Interface: () => Interface,
IpcSocketProvider: () => IpcSocketProvider,
JsonRpcApiProvider: () => JsonRpcApiProvider,
JsonRpcProvider: () => JsonRpcProvider,
JsonRpcSigner: () => JsonRpcSigner,
LangEn: () => LangEn,
Log: () => Log,
LogDescription: () => LogDescription,
MaxInt256: () => MaxInt256,
MaxUint256: () => MaxUint256,
MessagePrefix: () => MessagePrefix,
MinInt256: () => MinInt256,
Mnemonic: () => Mnemonic,
MulticoinProviderPlugin: () => MulticoinProviderPlugin,
N: () => N,
NamedFragment: () => NamedFragment,
Network: () => Network,
NetworkPlugin: () => NetworkPlugin,
NonceManager: () => NonceManager,
ParamType: () => ParamType,
PocketProvider: () => PocketProvider,
QuickNodeProvider: () => QuickNodeProvider,
Result: () => Result,
Signature: () => Signature,
SigningKey: () => SigningKey,
SocketBlockSubscriber: () => SocketBlockSubscriber,
SocketEventSubscriber: () => SocketEventSubscriber,
SocketPendingSubscriber: () => SocketPendingSubscriber,
SocketProvider: () => SocketProvider,
SocketSubscriber: () => SocketSubscriber,
StructFragment: () => StructFragment,
Transaction: () => Transaction,
TransactionDescription: () => TransactionDescription,
TransactionReceipt: () => TransactionReceipt,
TransactionResponse: () => TransactionResponse,
Typed: () => Typed,
TypedDataEncoder: () => TypedDataEncoder,
UndecodedEventLog: () => UndecodedEventLog,
UnmanagedSubscriber: () => UnmanagedSubscriber,
Utf8ErrorFuncs: () => Utf8ErrorFuncs,
VoidSigner: () => VoidSigner,
Wallet: () => Wallet,
WebSocketProvider: () => WebSocketProvider,
WeiPerEther: () => WeiPerEther,
Wordlist: () => Wordlist,
WordlistOwl: () => WordlistOwl,
WordlistOwlA: () => WordlistOwlA,
ZeroAddress: () => ZeroAddress,
ZeroHash: () => ZeroHash,
accessListify: () => accessListify,
assert: () => assert,
assertArgument: () => assertArgument,
assertArgumentCount: () => assertArgumentCount,
assertNormalize: () => assertNormalize,
assertPrivate: () => assertPrivate,
checkResultErrors: () => checkResultErrors,
computeAddress: () => computeAddress,
computeHmac: () => computeHmac,
concat: () => concat,
copyRequest: () => copyRequest,
dataLength: () => dataLength,
dataSlice: () => dataSlice,
decodeBase58: () => decodeBase58,
decodeBase64: () => decodeBase64,
decodeBytes32String: () => decodeBytes32String,
decodeRlp: () => decodeRlp,
decryptCrowdsaleJson: () => decryptCrowdsaleJson,
decryptKeystoreJson: () => decryptKeystoreJson,
decryptKeystoreJsonSync: () => decryptKeystoreJsonSync,
defaultPath: () => defaultPath2,
defineProperties: () => defineProperties,
dnsEncode: () => dnsEncode,
encodeBase58: () => encodeBase58,
encodeBase64: () => encodeBase64,
encodeBytes32String: () => encodeBytes32String,
encodeRlp: () => encodeRlp,
encryptKeystoreJson: () => encryptKeystoreJson,
encryptKeystoreJsonSync: () => encryptKeystoreJsonSync,
ensNormalize: () => ensNormalize,
formatEther: () => formatEther,
formatUnits: () => formatUnits,
fromTwos: () => fromTwos,
getAccountPath: () => getAccountPath,
getAddress: () => getAddress,
getBigInt: () => getBigInt,
getBytes: () => getBytes,
getBytesCopy: () => getBytesCopy,
getCreate2Address: () => getCreate2Address,
getCreateAddress: () => getCreateAddress,
getDefaultProvider: () => getDefaultProvider,
getIcapAddress: () => getIcapAddress,
getIndexedAccountPath: () => getIndexedAccountPath,
getNumber: () => getNumber,
getUint: () => getUint,
hashMessage: () => hashMessage,
hexlify: () => hexlify,
id: () => id,
isAddress: () => isAddress,
isAddressable: () => isAddressable,
isBytesLike: () => isBytesLike,
isCallException: () => isCallException,
isCrowdsaleJson: () => isCrowdsaleJson,
isError: () => isError,
isHexString: () => isHexString,
isKeystoreJson: () => isKeystoreJson,
isValidName: () => isValidName,
keccak256: () => keccak256,
lock: () => lock,
makeError: () => makeError,
mask: () => mask,
namehash: () => namehash,
parseEther: () => parseEther,
parseUnits: () => parseUnits,
pbkdf2: () => pbkdf22,
randomBytes: () => randomBytes3,
recoverAddress: () => recoverAddress,
resolveAddress: () => resolveAddress,
resolveProperties: () => resolveProperties,
ripemd160: () => ripemd1602,
scrypt: () => scrypt2,
scryptSync: () => scryptSync,
sha256: () => sha2562,
sha512: () => sha5122,
showThrottleMessage: () => showThrottleMessage,
solidityPacked: () => solidityPacked,
solidityPackedKeccak256: () => solidityPackedKeccak256,
solidityPackedSha256: () => solidityPackedSha256,
stripZerosLeft: () => stripZerosLeft,
toBeArray: () => toBeArray,
toBeHex: () => toBeHex,
toBigInt: () => toBigInt,
toNumber: () => toNumber,
toQuantity: () => toQuantity,
toTwos: () => toTwos,
toUtf8Bytes: () => toUtf8Bytes,
toUtf8CodePoints: () => toUtf8CodePoints,
toUtf8String: () => toUtf8String,
uuidV4: () => uuidV4,
verifyMessage: () => verifyMessage,
verifyTypedData: () => verifyTypedData,
version: () => version,
wordlists: () => wordlists,
zeroPadBytes: () => zeroPadBytes,
zeroPadValue: () => zeroPadValue
});
// node_modules/ethers/lib.esm/_version.js
var version = "6.9.1";
// node_modules/ethers/lib.esm/utils/properties.js
function checkType(value, type, name) {
const types = type.split("|").map((t) => t.trim());
for (let i = 0; i < types.length; i++) {
switch (type) {
case "any":
return;
case "bigint":
case "boolean":
case "number":
case "string":
if (typeof value === type) {
return;
}
}
}
const error = new Error(`invalid value for type ${type}`);
error.code = "INVALID_ARGUMENT";
error.argument = `value.${name}`;
error.value = value;
throw error;
}
async function resolveProperties(value) {
const keys = Object.keys(value);
const results = await Promise.all(keys.map((k) => Promise.resolve(value[k])));
return results.reduce((accum, v, index) => {
accum[keys[index]] = v;
return accum;
}, {});
}
function defineProperties(target, values, types) {
for (let key in values) {
let value = values[key];
const type = types ? types[key] : null;
if (type) {
checkType(value, type, key);
}
Object.defineProperty(target, key, { enumerable: true, value, writable: false });
}
}
// node_modules/ethers/lib.esm/utils/errors.js
function stringify(value) {
if (value == null) {
return "null";
}
if (Array.isArray(value)) {
return "[ " + value.map(stringify).join(", ") + " ]";
}
if (value instanceof Uint8Array) {
const HEX = "0123456789abcdef";
let result = "0x";
for (let i = 0; i < value.length; i++) {
result += HEX[value[i] >> 4];
result += HEX[value[i] & 15];
}
return result;
}
if (typeof value === "object" && typeof value.toJSON === "function") {
return stringify(value.toJSON());
}
switch (typeof value) {
case "boolean":
case "symbol":
return value.toString();
case "bigint":
return BigInt(value).toString();
case "number":
return value.toString();
case "string":
return JSON.stringify(value);
case "object": {
const keys = Object.keys(value);
keys.sort();
return "{ " + keys.map((k) => `${stringify(k)}: ${stringify(value[k])}`).join(", ") + " }";
}
}
return `[ COULD NOT SERIALIZE ]`;
}
function isError(error, code) {
return error && error.code === code;
}
function isCallException(error) {
return isError(error, "CALL_EXCEPTION");
}
function makeError(message, code, info) {
let shortMessage = message;
{
const details = [];
if (info) {
if ("message" in info || "code" in info || "name" in info) {
throw new Error(`value will overwrite populated values: ${stringify(info)}`);
}
for (const key in info) {
if (key === "shortMessage") {
continue;
}
const value = info[key];
details.push(key + "=" + stringify(value));
}
}
details.push(`code=${code}`);
details.push(`version=${version}`);
if (details.length) {
message += " (" + details.join(", ") + ")";
}
}
let error;
switch (code) {
case "INVALID_ARGUMENT":
error = new TypeError(message);
break;
case "NUMERIC_FAULT":
case "BUFFER_OVERRUN":
error = new RangeError(message);
break;
default:
error = new Error(message);
}
defineProperties(error, { code });
if (info) {
Object.assign(error, info);
}
if (error.shortMessage == null) {
defineProperties(error, { shortMessage });
}
return error;
}
function assert(check, message, code, info) {
if (!check) {
throw makeError(message, code, info);
}
}
function assertArgument(check, message, name, value) {
assert(check, message, "INVALID_ARGUMENT", { argument: name, value });
}
function assertArgumentCount(count, expectedCount, message) {
if (message == null) {
message = "";
}
if (message) {
message = ": " + message;
}
assert(count >= expectedCount, "missing arguemnt" + message, "MISSING_ARGUMENT", {
count,
expectedCount
});
assert(count <= expectedCount, "too many arguemnts" + message, "UNEXPECTED_ARGUMENT", {
count,
expectedCount
});
}
var _normalizeForms = ["NFD", "NFC", "NFKD", "NFKC"].reduce((accum, form) => {
try {
if ("test".normalize(form) !== "test") {
throw new Error("bad");
}
;
if (form === "NFD") {
const check = String.fromCharCode(233).normalize("NFD");
const expected = String.fromCharCode(101, 769);
if (check !== expected) {
throw new Error("broken");
}
}
accum.push(form);
} catch (error) {
}
return accum;
}, []);
function assertNormalize(form) {
assert(_normalizeForms.indexOf(form) >= 0, "platform missing String.prototype.normalize", "UNSUPPORTED_OPERATION", {
operation: "String.prototype.normalize",
info: { form }
});
}
function assertPrivate(givenGuard, guard, className) {
if (className == null) {
className = "";
}
if (givenGuard !== guard) {
let method = className, operation = "new";
if (className) {
method += ".";
operation += " " + className;
}
assert(false, `private constructor; use ${method}from* methods`, "UNSUPPORTED_OPERATION", {
operation
});
}
}
// node_modules/ethers/lib.esm/utils/data.js
function _getBytes(value, name, copy4) {
if (value instanceof Uint8Array) {
if (copy4) {
return new Uint8Array(value);
}
return value;
}
if (typeof value === "string" && value.match(/^0x([0-9a-f][0-9a-f])*$/i)) {
const result = new Uint8Array((value.length - 2) / 2);
let offset = 2;
for (let i = 0; i < result.length; i++) {
result[i] = parseInt(value.substring(offset, offset + 2), 16);
offset += 2;
}
return result;
}
assertArgument(false, "invalid BytesLike value", name || "value", value);
}
function getBytes(value, name) {
return _getBytes(value, name, false);
}
function getBytesCopy(value, name) {
return _getBytes(value, name, true);
}
function isHexString(value, length) {
if (typeof value !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) {
return false;
}
if (typeof length === "number" && value.length !== 2 + 2 * length) {
return false;
}
if (length === true && value.length % 2 !== 0) {
return false;
}
return true;
}
function isBytesLike(value) {
return isHexString(value, true) || value instanceof Uint8Array;
}
var HexCharacters = "0123456789abcdef";
function hexlify(data) {
const bytes2 = getBytes(data);
let result = "0x";
for (let i = 0; i < bytes2.length; i++) {
const v = bytes2[i];
result += HexCharacters[(v & 240) >> 4] + HexCharacters[v & 15];
}
return result;
}
function concat(datas) {
return "0x" + datas.map((d) => hexlify(d).substring(2)).join("");
}
function dataLength(data) {
if (isHexString(data, true)) {
return (data.length - 2) / 2;
}
return getBytes(data).length;
}
function dataSlice(data, start, end) {
const bytes2 = getBytes(data);
if (end != null && end > bytes2.length) {
assert(false, "cannot slice beyond data bounds", "BUFFER_OVERRUN", {
buffer: bytes2,
length: bytes2.length,
offset: end
});
}
return hexlify(bytes2.slice(start == null ? 0 : start, end == null ? bytes2.length : end));
}
function stripZerosLeft(data) {
let bytes2 = hexlify(data).substring(2);
while (bytes2.startsWith("00")) {
bytes2 = bytes2.substring(2);
}
return "0x" + bytes2;
}
function zeroPad(data, length, left) {
const bytes2 = getBytes(data);
assert(length >= bytes2.length, "padding exceeds data length", "BUFFER_OVERRUN", {
buffer: new Uint8Array(bytes2),
length,
offset: length + 1
});
const result = new Uint8Array(length);
result.fill(0);
if (left) {
result.set(bytes2, length - bytes2.length);
} else {
result.set(bytes2, 0);
}
return hexlify(result);
}
function zeroPadValue(data, length) {
return zeroPad(data, length, true);
}
function zeroPadBytes(data, length) {
return zeroPad(data, length, false);
}
// node_modules/ethers/lib.esm/utils/maths.js
var BN_0 = BigInt(0);
var BN_1 = BigInt(1);
var maxValue = 9007199254740991;
function fromTwos(_value, _width) {
const value = getUint(_value, "value");
const width = BigInt(getNumber(_width, "width"));
assert(value >> width === BN_0, "overflow", "NUMERIC_FAULT", {
operation: "fromTwos",
fault: "overflow",
value: _value
});
if (value >> width - BN_1) {
const mask2 = (BN_1 << width) - BN_1;
return -((~value & mask2) + BN_1);
}
return value;
}
function toTwos(_value, _width) {
let value = getBigInt(_value, "value");
const width = BigInt(getNumber(_width, "width"));
const limit = BN_1 << width - BN_1;
if (value < BN_0) {
value = -value;
assert(value <= limit, "too low", "NUMERIC_FAULT", {
operation: "toTwos",
fault: "overflow",
value: _value
});
const mask2 = (BN_1 << width) - BN_1;
return (~value & mask2) + BN_1;
} else {
assert(value < limit, "too high", "NUMERIC_FAULT", {
operation: "toTwos",
fault: "overflow",
value: _value
});
}
return value;
}
function mask(_value, _bits) {
const value = getUint(_value, "value");
const bits = BigInt(getNumber(_bits, "bits"));
return value & (BN_1 << bits) - BN_1;
}
function getBigInt(value, name) {
switch (typeof value) {
case "bigint":
return value;
case "number":
assertArgument(Number.isInteger(value), "underflow", name || "value", value);
assertArgument(value >= -maxValue && value <= maxValue, "overflow", name || "value", value);
return BigInt(value);
case "string":
try {
if (value === "") {
throw new Error("empty string");
}
if (value[0] === "-" && value[1] !== "-") {
return -BigInt(value.substring(1));
}
return BigInt(value);
} catch (e) {
assertArgument(false, `invalid BigNumberish string: ${e.message}`, name || "value", value);
}
}
assertArgument(false, "invalid BigNumberish value", name || "value", value);
}
function getUint(value, name) {
const result = getBigInt(value, name);
assert(result >= BN_0, "unsigned value cannot be negative", "NUMERIC_FAULT", {
fault: "overflow",
operation: "getUint",
value
});
return result;
}
var Nibbles = "0123456789abcdef";
function toBigInt(value) {
if (value instanceof Uint8Array) {
let result = "0x0";
for (const v of value) {
result += Nibbles[v >> 4];
result += Nibbles[v & 15];
}
return BigInt(result);
}
return getBigInt(value);
}
function getNumber(value, name) {
switch (typeof value) {
case "bigint":
assertArgument(value >= -maxValue && value <= maxValue, "overflow", name || "value", value);
return Number(value);
case "number":
assertArgument(Number.isInteger(value), "underflow", name || "value", value);
assertArgument(value >= -maxValue && value <= maxValue, "overflow", name || "value", value);
return value;
case "string":
try {
if (value === "") {
throw new Error("empty string");
}
return getNumber(BigInt(value), name);
} catch (e) {
assertArgument(false, `invalid numeric string: ${e.message}`, name || "value", value);
}
}
assertArgument(false, "invalid numeric value", name || "value", value);
}
function toNumber(value) {
return getNumber(toBigInt(value));
}
function toBeHex(_value, _width) {
const value = getUint(_value, "value");
let result = value.toString(16);
if (_width == null) {
if (result.length % 2) {
result = "0" + result;
}
} else {
const width = getNumber(_width, "width");
assert(width * 2 >= result.length, `value exceeds width (${width} bytes)`, "NUMERIC_FAULT", {
operation: "toBeHex",
fault: "overflow",
value: _value
});
while (result.length < width * 2) {
result = "0" + result;
}
}
return "0x" + result;
}
function toBeArray(_value) {
const value = getUint(_value, "value");
if (value === BN_0) {
return new Uint8Array([]);
}
let hex = value.toString(16);
if (hex.length % 2) {
hex = "0" + hex;
}
const result = new Uint8Array(hex.length / 2);
for (let i = 0; i < result.length; i++) {
const offset = i * 2;
result[i] = parseInt(hex.substring(offset, offset + 2), 16);
}
return result;
}
function toQuantity(value) {
let result = hexlify(isBytesLike(value) ? value : toBeArray(value)).substring(2);
while (result.startsWith("0")) {
result = result.substring(1);
}
if (result === "") {
result = "0";
}
return "0x" + result;
}
// node_modules/ethers/lib.esm/utils/base58.js
var Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
var Lookup = null;
function getAlpha(letter) {
if (Lookup == null) {
Lookup = {};
for (let i = 0; i < Alphabet.length; i++) {
Lookup[Alphabet[i]] = BigInt(i);
}
}
const result = Lookup[letter];
assertArgument(result != null, `invalid base58 value`, "letter", letter);
return result;
}
var BN_02 = BigInt(0);
var BN_58 = BigInt(58);
function encodeBase58(_value) {
let value = toBigInt(getBytes(_value));
let result = "";
while (value) {
result = Alphabet[Number(value % BN_58)] + result;
value /= BN_58;
}
return result;
}
function decodeBase58(value) {
let result = BN_02;
for (let i = 0; i < value.length; i++) {
result *= BN_58;
result += getAlpha(value[i]);
}
return result;
}
// node_modules/ethers/lib.esm/utils/base64-browser.js
function decodeBase64(textData) {
textData = atob(textData);
const data = new Uint8Array(textData.length);
for (let i = 0; i < textData.length; i++) {
data[i] = textData.charCodeAt(i);
}
return getBytes(data);
}
function encodeBase64(_data) {
const data = getBytes(_data);
let textData = "";
for (let i = 0; i < data.length; i++) {
textData += String.fromCharCode(data[i]);
}
return btoa(textData);
}
// node_modules/ethers/lib.esm/utils/events.js
var EventPayload = class {
/**
* The event filter.
*/
filter;
/**
* The **EventEmitterable**.
*/
emitter;
#listener;
/**
* Create a new **EventPayload** for %%emitter%% with
* the %%listener%% and for %%filter%%.
*/
constructor(emitter, listener, filter) {
this.#listener = listener;
defineProperties(this, { emitter, filter });
}
/**
* Unregister the triggered listener for future events.
*/
async removeListener() {
if (this.#listener == null) {
return;
}
await this.emitter.off(this.filter, this.#listener);
}
};
// node_modules/ethers/lib.esm/utils/utf8.js
function errorFunc(reason, offset, bytes2, output2, badCodepoint) {
assertArgument(false, `invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes2);
}
function ignoreFunc(reason, offset, bytes2, output2, badCodepoint) {
if (reason === "BAD_PREFIX" || reason === "UNEXPECTED_CONTINUE") {
let i = 0;
for (let o = offset + 1; o < bytes2.length; o++) {
if (bytes2[o] >> 6 !== 2) {
break;
}
i++;
}
return i;
}
if (reason === "OVERRUN") {
return bytes2.length - offset - 1;
}
return 0;
}
function replaceFunc(reason, offset, bytes2, output2, badCodepoint) {
if (reason === "OVERLONG") {
assertArgument(typeof badCodepoint === "number", "invalid bad code point for replacement", "badCodepoint", badCodepoint);
output2.push(badCodepoint);
return 0;
}
output2.push(65533);
return ignoreFunc(reason, offset, bytes2, output2, badCodepoint);
}
var Utf8ErrorFuncs = Object.freeze({
error: errorFunc,
ignore: ignoreFunc,
replace: replaceFunc
});
function getUtf8CodePoints(_bytes, onError) {
if (onError == null) {
onError = Utf8ErrorFuncs.error;
}
const bytes2 = getBytes(_bytes, "bytes");
const result = [];
let i = 0;
while (i < bytes2.length) {
const c = bytes2[i++];
if (c >> 7 === 0) {
result.push(c);
continue;
}
let extraLength = null;
let overlongMask = null;
if ((c & 224) === 192) {
extraLength = 1;
overlongMask = 127;
} else if ((c & 240) === 224) {
extraLength = 2;
overlongMask = 2047;
} else if ((c & 248) === 240) {
extraLength = 3;
overlongMask = 65535;
} else {
if ((c & 192) === 128) {
i += onError("UNEXPECTED_CONTINUE", i - 1, bytes2, result);
} else {
i += onError("BAD_PREFIX", i - 1, bytes2, result);
}
continue;
}
if (i - 1 + extraLength >= bytes2.length) {
i += onError("OVERRUN", i - 1, bytes2, result);
continue;
}
let res = c & (1 << 8 - extraLength - 1) - 1;
for (let j = 0; j < extraLength; j++) {
let nextChar = bytes2[i];
if ((nextChar & 192) != 128) {
i += onError("MISSING_CONTINUE", i, bytes2, result);
res = null;
break;
}
;
res = res << 6 | nextChar & 63;
i++;
}
if (res === null) {
continue;
}
if (res > 1114111) {
i += onError("OUT_OF_RANGE", i - 1 - extraLength, bytes2, result, res);
continue;
}
if (res >= 55296 && res <= 57343) {
i += onError("UTF16_SURROGATE", i - 1 - extraLength, bytes2, result, res);
continue;
}
if (res <= overlongMask) {
i += onError("OVERLONG", i - 1 - extraLength, bytes2, result, res);
continue;
}
result.push(res);
}
return result;
}
function toUtf8Bytes(str, form) {
if (form != null) {
assertNormalize(form);
str = str.normalize(form);
}
let result = [];
for (let i = 0; i < str.length; i++) {
const c = str.charCodeAt(i);
if (c < 128) {
result.push(c);
} else if (c < 2048) {
result.push(c >> 6 | 192);
result.push(c & 63 | 128);
} else if ((c & 64512) == 55296) {
i++;
const c2 = str.charCodeAt(i);
assertArgument(i < str.length && (c2 & 64512) === 56320, "invalid surrogate pair", "str", str);
const pair = 65536 + ((c & 1023) << 10) + (c2 & 1023);
result.push(pair >> 18 | 240);
result.push(pair >> 12 & 63 | 128);
result.push(pair >> 6 & 63 | 128);
result.push(pair & 63 | 128);
} else {
result.push(c >> 12 | 224);
result.push(c >> 6 & 63 | 128);
result.push(c & 63 | 128);
}
}
return new Uint8Array(result);
}
function _toUtf8String(codePoints) {
return codePoints.map((codePoint) => {
if (codePoint <= 65535) {
return String.fromCharCode(codePoint);
}
codePoint -= 65536;
return String.fromCharCode((codePoint >> 10 & 1023) + 55296, (codePoint & 1023) + 56320);
}).join("");
}
function toUtf8String(bytes2, onError) {
return _toUtf8String(getUtf8CodePoints(bytes2, onError));
}
function toUtf8CodePoints(str, form) {
return getUtf8CodePoints(toUtf8Bytes(str, form));
}
// node_modules/ethers/lib.esm/utils/geturl-browser.js
function createGetUrl(options) {
async function getUrl(req, _signal) {
const protocol = req.url.split(":")[0].toLowerCase();
assert(protocol === "http" || protocol === "https", `unsupported protocol ${protocol}`, "UNSUPPORTED_OPERATION", {
info: { protocol },
operation: "request"
});
assert(protocol === "https" || !req.credentials || req.allowInsecureAuthentication, "insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", {
operation: "request"
});
let signal = void 0;
if (_signal) {
const controller = new AbortController();
signal = controller.signal;
_signal.addListener(() => {
controller.abort();
});
}
const init2 = {
method: req.method,
headers: new Headers(Array.from(req)),
body: req.body || void 0,
signal
};
const resp = await fetch(req.url, init2);
const headers = {};
resp.headers.forEach((value, key) => {
headers[key.toLowerCase()] = value;
});
const respBody = await resp.arrayBuffer();
const body = respBody == null ? null : new Uint8Array(respBody);
return {
statusCode: resp.status,
statusMessage: resp.statusText,
headers,
body
};
}
return getUrl;
}
var defaultGetUrl = createGetUrl({});
// node_modules/ethers/lib.esm/utils/fetch.js
var MAX_ATTEMPTS = 12;
var SLOT_INTERVAL = 250;
var defaultGetUrlFunc = createGetUrl();
var reData = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i");
var reIpfs = new RegExp("^ipfs://(ipfs/)?(.*)$", "i");
var locked = false;
async function dataGatewayFunc(url, signal) {
try {
const match = url.match(reData);
if (!match) {
throw new Error("invalid data");
}
return new FetchResponse(200, "OK", {
"content-type": match[1] || "text/plain"
}, match[2] ? decodeBase64(match[3]) : unpercent(match[3]));
} catch (error) {
return new FetchResponse(599, "BAD REQUEST (invalid data: URI)", {}, null, new FetchRequest(url));
}
}
function getIpfsGatewayFunc(baseUrl) {
async function gatewayIpfs(url, signal) {
try {
const match = url.match(reIpfs);
if (!match) {
throw new Error("invalid link");
}
return new FetchRequest(`${baseUrl}${match[2]}`);
} catch (error) {
return new FetchResponse(599, "BAD REQUEST (invalid IPFS URI)", {}, null, new FetchRequest(url));
}
}
return gatewayIpfs;
}
var Gateways = {
"data": dataGatewayFunc,
"ipfs": getIpfsGatewayFunc("https://gateway.ipfs.io/ipfs/")
};
var fetchSignals = /* @__PURE__ */ new WeakMap();
var FetchCancelSignal = class {
#listeners;
#cancelled;
constructor(request) {
this.#listeners = [];
this.#cancelled = false;
fetchSignals.set(request, () => {
if (this.#cancelled) {
return;
}
this.#cancelled = true;
for (const listener of this.#listeners) {
setTimeout(() => {
listener();
}, 0);
}
this.#listeners = [];
});
}
addListener(listener) {
assert(!this.#cancelled, "singal already cancelled", "UNSUPPORTED_OPERATION", {
operation: "fetchCancelSignal.addCancelListener"
});
this.#listeners.push(listener);
}
get cancelled() {
return this.#cancelled;
}
checkSignal() {
assert(!this.cancelled, "cancelled", "CANCELLED", {});
}
};
function checkSignal(signal) {
if (signal == null) {
throw new Error("missing signal; should not happen");
}
signal.checkSignal();
return signal;
}
var FetchRequest = class _FetchRequest {
#allowInsecure;
#gzip;
#headers;
#method;
#timeout;
#url;
#body;
#bodyType;
#creds;
// Hooks
#preflight;
#process;
#retry;
#signal;
#throttle;
#getUrlFunc;
/**
* The fetch URL to request.
*/
get url() {
return this.#url;
}
set url(url) {
this.#url = String(url);
}
/**
* The fetch body, if any, to send as the request body. //(default: null)//
*
* When setting a body, the intrinsic ``Content-Type`` is automatically
* set and will be used if **not overridden** by setting a custom
* header.
*
* If %%body%% is null, the body is cleared (along with the
* intrinsic ``Content-Type``).
*
* If %%body%% is a string, the intrinsic ``Content-Type`` is set to
* ``text/plain``.
*
* If %%body%% is a Uint8Array, the intrinsic ``Content-Type`` is set to
* ``application/octet-stream``.
*
* If %%body%% is any other object, the intrinsic ``Content-Type`` is
* set to ``application/json``.
*/
get body() {
if (this.#body == null) {
return null;
}
return new Uint8Array(this.#body);
}
set body(body) {
if (body == null) {
this.#body = void 0;
this.#bodyType = void 0;
} else if (typeof body === "string") {
this.#body = toUtf8Bytes(body);
this.#bodyType = "text/plain";
} else if (body instanceof Uint8Array) {
this.#body = body;
this.#bodyType = "application/octet-stream";
} else if (typeof body === "object") {
this.#body = toUtf8Bytes(JSON.stringify(body));
this.#bodyType = "application/json";
} else {
throw new Error("invalid body");
}
}
/**
* Returns true if the request has a body.
*/
hasBody() {
return this.#body != null;
}
/**
* The HTTP method to use when requesting the URI. If no method
* has been explicitly set, then ``GET`` is used if the body is
* null and ``POST`` otherwise.
*/
get method() {
if (this.#method) {
return this.#method;
}
if (this.hasBody()) {
return "POST";
}
return "GET";
}
set method(method) {
if (method == null) {
method = "";
}
this.#method = String(method).toUpperCase();
}
/**
* The headers that will be used when requesting the URI. All
* keys are lower-case.
*
* This object is a copy, so any changes will **NOT** be reflected
* in the ``FetchRequest``.
*
* To set a header entry, use the ``setHeader`` method.
*/
get headers() {
const headers = Object.assign({}, this.#headers);
if (this.#creds) {
headers["authorization"] = `Basic ${encodeBase64(toUtf8Bytes(this.#creds))}`;
}
;
if (this.allowGzip) {
headers["accept-encoding"] = "gzip";
}
if (headers["content-type"] == null && this.#bodyType) {
headers["content-type"] = this.#bodyType;
}
if (this.body) {
headers["content-length"] = String(this.body.length);
}
return headers;
}
/**
* Get the header for %%key%%, ignoring case.
*/
getHeader(key) {
return this.headers[key.toLowerCase()];
}
/**
* Set the header for %%key%% to %%value%%. All values are coerced
* to a string.
*/
setHeader(key, value) {
this.#headers[String(key).toLowerCase()] = String(value);
}
/**
* Clear all headers, resetting all intrinsic headers.
*/
clearHeaders() {
this.#headers = {};
}
[Symbol.iterator]() {
const headers = this.headers;
const keys = Object.keys(headers);
let index = 0;
return {
next: () => {
if (index < keys.length) {
const key = keys[index++];
return {
value: [key, headers[key]],
done: false
};
}
return { value: void 0, done: true };
}
};
}
/**
* The value that will be sent for the ``Authorization`` header.
*
* To set the credentials, use the ``setCredentials`` method.
*/
get credentials() {
return this.#creds || null;
}
/**
* Sets an ``Authorization`` for %%username%% with %%password%%.
*/
setCredentials(username, password) {
assertArgument(!username.match(/:/), "invalid basic authentication username", "username", "[REDACTED]");
this.#creds = `${username}:${password}`;
}
/**
* Enable and request gzip-encoded responses. The response will
* automatically be decompressed. //(default: true)//
*/
get allowGzip() {
return this.#gzip;
}
set allowGzip(value) {
this.#gzip = !!value;
}
/**
* Allow ``Authentication`` credentials to be sent over insecure
* channels. //(default: false)//
*/
get allowInsecureAuthentication() {
return !!this.#allowInsecure;
}
set allowInsecureAuthentication(value) {
this.#allowInsecure = !!value;
}
/**
* The timeout (in milliseconds) to wait for a complete response.
* //(default: 5 minutes)//
*/
get timeout() {
return this.#timeout;
}
set timeout(timeout) {
assertArgument(timeout >= 0, "timeout must be non-zero", "timeout", timeout);
this.#timeout = timeout;
}
/**
* This function is called prior to each request, for example
* during a redirection or retry in case of server throttling.
*
* This offers an opportunity to populate headers or update
* content before sending a request.
*/
get preflightFunc() {
return this.#preflight || null;
}
set preflightFunc(preflight) {
this.#preflight = preflight;
}
/**
* This function is called after each response, offering an
* opportunity to provide client-level throttling or updating
* response data.
*
* Any error thrown in this causes the ``send()`` to throw.
*
* To schedule a retry attempt (assuming the maximum retry limit
* has not been reached), use [[response.throwThrottleError]].
*/
get processFunc() {
return this.#process || null;
}
set processFunc(process) {
this.#process = process;
}
/**
* This function is called on each retry attempt.
*/
get retryFunc() {
return this.#retry || null;
}
set retryFunc(retry) {
this.#retry = retry;
}
/**
* This function is called to fetch content from HTTP and
* HTTPS URLs and is platform specific (e.g. nodejs vs
* browsers).
*
* This is by default the currently registered global getUrl
* function, which can be changed using [[registerGetUrl]].
* If this has been set, setting is to ``null`` will cause
* this FetchRequest (and any future clones) to revert back to
* using the currently registered global getUrl function.
*
* Setting this is generally not necessary, but may be useful
* for developers that wish to intercept requests or to
* configurege a proxy or other agent.
*/
get getUrlFunc() {
return this.#getUrlFunc || defaultGetUrlFunc;
}
set getUrlFunc(value) {
this.#getUrlFunc = value;
}
/**
* Create a new FetchRequest instance with default values.
*
* Once created, each property may be set before issuing a
* ``.send()`` to make the request.
*/
constructor(url) {
this.#url = String(url);
this.#allowInsecure = false;
this.#gzip = true;
this.#headers = {};
this.#method = "";
this.#timeout = 3e5;
this.#throttle = {
slotInterval: SLOT_INTERVAL,
maxAttempts: MAX_ATTEMPTS
};
this.#getUrlFunc = null;
}
toString() {
return `<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${this.#body ? hexlify(this.#body) : "null"}>`;
}
/**
* Update the throttle parameters used to determine maximum
* attempts and exponential-backoff properties.
*/
setThrottleParams(params) {
if (params.slotInterval != null) {
this.#throttle.slotInterval = params.slotInterval;
}
if (params.maxAttempts != null) {
this.#throttle.maxAttempts = params.maxAttempts;
}
}
async #send(attempt, expires, delay, _request, _response) {
if (attempt >= this.#throttle.maxAttempts) {
return _response.makeServerError("exceeded maximum retry limit");
}
assert(getTime() <= expires, "timeout", "TIMEOUT", {
operation: "request.send",
reason: "timeout",
request: _request
});
if (delay > 0) {
await wait(delay);
}
let req = this.clone();
const scheme = (req.url.split(":")[0] || "").toLowerCase();
if (scheme in Gateways) {
const result = await Gateways[scheme](req.url, checkSignal(_request.#signal));
if (result instanceof FetchResponse) {
let response2 = result;
if (this.processFunc) {
checkSignal(_request.#signal);
try {
response2 = await this.processFunc(req, response2);
} catch (error) {
if (error.throttle == null || typeof error.stall !== "number") {
response2.makeServerError("error in post-processing function", error).assertOk();
}
}
}
return response2;
}
req = result;
}
if (this.preflightFunc) {
req = await this.preflightFunc(req);
}
const resp = await this.getUrlFunc(req, checkSignal(_request.#signal));
let response = new FetchResponse(resp.statusCode, resp.statusMessage, resp.headers, resp.body, _request);
if (response.statusCode === 301 || response.statusCode === 302) {
try {
const location = response.headers.location || "";
return req.redirect(location).#send(attempt + 1, expires, 0, _request, response);
} catch (error) {
}
return response;
} else if (response.statusCode === 429) {
if (this.retryFunc == null || await this.retryFunc(req, response, attempt)) {
const retryAfter = response.headers["retry-after"];
let delay2 = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt));
if (typeof retryAfter === "string" && retryAfter.match(/^[1-9][0-9]*$/)) {
delay2 = parseInt(retryAfter);
}
return req.clone().#send(attempt + 1, expires, delay2, _request, response);
}
}
if (this.processFunc) {
checkSignal(_request.#signal);
try {
response = await this.processFunc(req, response);
} catch (error) {
if (error.throttle == null || typeof error.stall !== "number") {
response.makeServerError("error in post-processing function", error).assertOk();
}
let delay2 = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt));
;
if (error.stall >= 0) {
delay2 = error.stall;
}
return req.clone().#send(attempt + 1, expires, delay2, _request, response);
}
}
return response;
}
/**
* Resolves to the response by sending the request.
*/
send() {
assert(this.#signal == null, "request already sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.send" });
this.#signal = new FetchCancelSignal(this);
return this.#send(0, getTime() + this.timeout, 0, this, new FetchResponse(0, "", {}, null, this));
}
/**
* Cancels the inflight response, causing a ``CANCELLED``
* error to be rejected from the [[send]].
*/
cancel() {
assert(this.#signal != null, "request has not been sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.cancel" });
const signal = fetchSignals.get(this);
if (!signal) {
throw new Error("missing signal; should not happen");
}
signal();
}
/**
* Returns a new [[FetchRequest]] that represents the redirection
* to %%location%%.
*/
redirect(location) {
const current = this.url.split(":")[0].toLowerCase();
const target = location.split(":")[0].toLowerCase();
assert(this.method === "GET" && (current !== "https" || target !== "http") && location.match(/^https?:/), `unsupported redirect`, "UNSUPPORTED_OPERATION", {
operation: `redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location)})`
});
const req = new _FetchRequest(location);
req.method = "GET";
req.allowGzip = this.allowGzip;
req.timeout = this.timeout;
req.#headers = Object.assign({}, this.#headers);
if (this.#body) {
req.#body = new Uint8Array(this.#body);
}
req.#bodyType = this.#bodyType;
return req;
}
/**
* Create a new copy of this request.
*/
clone() {
const clone = new _FetchRequest(this.url);
clone.#method = this.#method;
if (this.#body) {
clone.#body = this.#body;
}
clone.#bodyType = this.#bodyType;
clone.#headers = Object.assign({}, this.#headers);
clone.#creds = this.#creds;
if (this.allowGzip) {
clone.allowGzip = true;
}
clone.timeout = this.timeout;
if (this.allowInsecureAuthentication) {
clone.allowInsecureAuthentication = true;
}
clone.#preflight = this.#preflight;
clone.#process = this.#process;
clone.#retry = this.#retry;
clone.#getUrlFunc = this.#getUrlFunc;
return clone;
}
/**
* Locks all static configuration for gateways and FetchGetUrlFunc
* registration.
*/
static lockConfig() {
locked = true;
}
/**
* Get the current Gateway function for %%scheme%%.
*/
static getGateway(scheme) {
return Gateways[scheme.toLowerCase()] || null;
}
/**
* Use the %%func%% when fetching URIs using %%scheme%%.
*
* This method affects all requests globally.
*
* If [[lockConfig]] has been called, no change is made and this
* throws.
*/
static registerGateway(scheme, func) {
scheme = scheme.toLowerCase();
if (scheme === "http" || scheme === "https") {
throw new Error(`cannot intercept ${scheme}; use registerGetUrl`);
}
if (locked) {
throw new Error("gateways locked");
}
Gateways[scheme] = func;
}
/**
* Use %%getUrl%% when fetching URIs over HTTP and HTTPS requests.
*
* This method affects all requests globally.
*
* If [[lockConfig]] has been called, no change is made and this
* throws.
*/
static registerGetUrl(getUrl) {
if (locked) {
throw new Error("gateways locked");
}
defaultGetUrlFunc = getUrl;
}
/**
* Creates a getUrl function that fetches content from HTTP and
* HTTPS URLs.
*
* The available %%options%% are dependent on the platform
* implementation of the default getUrl function.
*
* This is not generally something that is needed, but is useful
* when trying to customize simple behaviour when fetching HTTP
* content.
*/
static createGetUrlFunc(options) {
return createGetUrl(options);
}
/**
* Creates a function that can "fetch" data URIs.
*
* Note that this is automatically done internally to support
* data URIs, so it is not necessary to register it.
*
* This is not generally something that is needed, but may
* be useful in a wrapper to perfom custom data URI functionality.
*/
static createDataGateway() {
return dataGatewayFunc;
}
/**
* Creates a function that will fetch IPFS (unvalidated) from
* a custom gateway baseUrl.
*
* The default IPFS gateway used internally is
* ``"https:/\/gateway.ipfs.io/ipfs/"``.
*/
static createIpfsGatewayFunc(baseUrl) {
return getIpfsGatewayFunc(baseUrl);
}
};
var FetchResponse = class _FetchResponse {
#statusCode;
#statusMessage;
#headers;
#body;
#request;
#error;
toString() {
return `<FetchResponse status=${this.statusCode} body=${this.#body ? hexlify(this.#body) : "null"}>`;
}
/**
* The response status code.
*/
get statusCode() {
return this.#statusCode;
}
/**
* The response status message.
*/
get statusMessage() {
return this.#statusMessage;
}
/**
* The response headers. All keys are lower-case.
*/
get headers() {
return Object.assign({}, this.#headers);
}
/**
* The response body, or ``null`` if there was no body.
*/
get body() {
return this.#body == null ? null : new Uint8Array(this.#body);
}
/**
* The response body as a UTF-8 encoded string, or the empty
* string (i.e. ``""``) if there was no body.
*
* An error is thrown if the body is invalid UTF-8 data.
*/
get bodyText() {
try {
return this.#body == null ? "" : toUtf8String(this.#body);
} catch (error) {
assert(false, "response body is not valid UTF-8 data", "UNSUPPORTED_OPERATION", {
operation: "bodyText",
info: { response: this }
});
}
}
/**
* The response body, decoded as JSON.
*
* An error is thrown if the body is invalid JSON-encoded data
* or if there was no body.
*/
get bodyJson() {
try {
return JSON.parse(this.bodyText);
} catch (error) {
assert(false, "response body is not valid JSON", "UNSUPPORTED_OPERATION", {
operation: "bodyJson",
info: { response: this }
});
}
}
[Symbol.iterator]() {
const headers = this.headers;
const keys = Object.keys(headers);
let index = 0;
return {
next: () => {
if (index < keys.length) {
const key = keys[index++];
return {
value: [key, headers[key]],
done: false
};
}
return { value: void 0, done: true };
}
};
}
constructor(statusCode, statusMessage, headers, body, request) {
this.#statusCode = statusCode;
this.#statusMessage = statusMessage;
this.#headers = Object.keys(headers).reduce((accum, k) => {
accum[k.toLowerCase()] = String(headers[k]);
return accum;
}, {});
this.#body = body == null ? null : new Uint8Array(body);
this.#request = request || null;
this.#error = { message: "" };
}
/**
* Return a Response with matching headers and body, but with
* an error status code (i.e. 599) and %%message%% with an
* optional %%error%%.
*/
makeServerError(message, error) {
let statusMessage;
if (!message) {
message = `${this.statusCode} ${this.statusMessage}`;
statusMessage = `CLIENT ESCALATED SERVER ERROR (${message})`;
} else {
statusMessage = `CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`;
}
const response = new _FetchResponse(599, statusMessage, this.headers, this.body, this.#request || void 0);
response.#error = { message, error };
return response;
}
/**
* If called within a [request.processFunc](FetchRequest-processFunc)
* call, causes the request to retry as if throttled for %%stall%%
* milliseconds.
*/
throwThrottleError(message, stall5) {
if (stall5 == null) {
stall5 = -1;
} else {
assertArgument(Number.isInteger(stall5) && stall5 >= 0, "invalid stall timeout", "stall", stall5);
}
const error = new Error(message || "throttling requests");
defineProperties(error, { stall: stall5, throttle: true });
throw error;
}
/**
* Get the header value for %%key%%, ignoring case.
*/
getHeader(key) {
return this.headers[key.toLowerCase()];
}
/**
* Returns true if the response has a body.
*/
hasBody() {
return this.#body != null;
}
/**
* The request made for this response.
*/
get request() {
return this.#request;
}
/**
* Returns true if this response was a success statusCode.
*/
ok() {
return this.#error.message === "" && this.statusCode >= 200 && this.statusCode < 300;
}
/**
* Throws a ``SERVER_ERROR`` if this response is not ok.
*/
assertOk() {
if (this.ok()) {
return;
}
let { message, error } = this.#error;
if (message === "") {
message = `server response ${this.statusCode} ${this.statusMessage}`;
}
assert(false, message, "SERVER_ERROR", {
request: this.request || "unknown request",
response: this,
error
});
}
};
function getTime() {
return (/* @__PURE__ */ new Date()).getTi