2022-11-05 01:08:37 +03:00
|
|
|
import { assert, assertArgument } from "../utils/index.js";
|
2022-09-05 23:14:43 +03:00
|
|
|
|
|
|
|
import { getAddress } from "./address.js";
|
|
|
|
|
|
|
|
import type { Addressable, AddressLike, NameResolver } from "./index.js";
|
|
|
|
|
|
|
|
|
2022-12-03 05:23:13 +03:00
|
|
|
/**
|
|
|
|
* Returns true if %%value%% is an object which implements the
|
|
|
|
* [[Addressable]] interface.
|
|
|
|
*/
|
2022-09-05 23:14:43 +03:00
|
|
|
export function isAddressable(value: any): value is Addressable {
|
|
|
|
return (value && typeof(value.getAddress) === "function");
|
|
|
|
}
|
|
|
|
|
2022-12-03 05:23:13 +03:00
|
|
|
/**
|
|
|
|
* Returns true if %%value%% is a valid address.
|
|
|
|
*/
|
2022-09-05 23:14:43 +03:00
|
|
|
export function isAddress(value: any): boolean {
|
|
|
|
try {
|
|
|
|
getAddress(value);
|
|
|
|
return true;
|
|
|
|
} catch (error) { }
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
async function checkAddress(target: any, promise: Promise<null | string>): Promise<string> {
|
|
|
|
const result = await promise;
|
|
|
|
if (result == null || result === "0x0000000000000000000000000000000000000000") {
|
2022-11-05 01:08:37 +03:00
|
|
|
assert(typeof(target) !== "string", "unconfigured name", "UNCONFIGURED_NAME", { value: target });
|
2022-10-25 11:06:00 +03:00
|
|
|
assertArgument(false, "invalid AddressLike value; did not resolve to a value address", "target", target);
|
2022-09-05 23:14:43 +03:00
|
|
|
}
|
|
|
|
return getAddress(result);
|
|
|
|
}
|
|
|
|
|
2022-12-03 05:23:13 +03:00
|
|
|
/**
|
|
|
|
* Resolves to an address for the %%target%%, which may be any
|
|
|
|
* supported address type, an [[Addressable]] or a Promise which
|
|
|
|
* resolves to an address.
|
|
|
|
*
|
|
|
|
* If an ENS name is provided, but that name has not been correctly
|
|
|
|
* configured a [[UnconfiguredNameError]] is thrown.
|
|
|
|
*/
|
2022-09-05 23:14:43 +03:00
|
|
|
export function resolveAddress(target: AddressLike, resolver?: null | NameResolver): string | Promise<string> {
|
|
|
|
|
|
|
|
if (typeof(target) === "string") {
|
|
|
|
if (target.match(/^0x[0-9a-f]{40}$/i)) { return getAddress(target); }
|
|
|
|
|
2022-11-05 01:08:37 +03:00
|
|
|
assert(resolver != null, "ENS resolution requires a provider",
|
|
|
|
"UNSUPPORTED_OPERATION", { operation: "resolveName" });
|
2022-09-05 23:14:43 +03:00
|
|
|
|
|
|
|
return checkAddress(target, resolver.resolveName(target));
|
|
|
|
|
|
|
|
} else if (isAddressable(target)) {
|
|
|
|
return checkAddress(target, target.getAddress());
|
|
|
|
|
|
|
|
} else if (typeof(target.then) === "function") {
|
|
|
|
return checkAddress(target, target);
|
|
|
|
}
|
|
|
|
|
2022-10-25 11:06:00 +03:00
|
|
|
assertArgument(false, "unsupported addressable value", "target", target);
|
2022-09-05 23:14:43 +03:00
|
|
|
}
|