network.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. /**
  2. * A **Network** encapsulates the various properties required to
  3. * interact with a specific chain.
  4. *
  5. * @_subsection: api/providers:Networks [networks]
  6. */
  7. import { accessListify } from "../transaction/index.js";
  8. import { getBigInt, assert, assertArgument } from "../utils/index.js";
  9. import {
  10. EnsPlugin, FetchUrlFeeDataNetworkPlugin, GasCostPlugin
  11. } from "./plugins-network.js";
  12. import type { BigNumberish } from "../utils/index.js";
  13. import type { TransactionLike } from "../transaction/index.js";
  14. import type { NetworkPlugin } from "./plugins-network.js";
  15. /**
  16. * A Networkish can be used to allude to a Network, by specifing:
  17. * - a [[Network]] object
  18. * - a well-known (or registered) network name
  19. * - a well-known (or registered) chain ID
  20. * - an object with sufficient details to describe a network
  21. */
  22. export type Networkish = Network | number | bigint | string | {
  23. name?: string,
  24. chainId?: number,
  25. //layerOneConnection?: Provider,
  26. ensAddress?: string,
  27. ensNetwork?: number
  28. };
  29. /* * * *
  30. // Networks which operation against an L2 can use this plugin to
  31. // specify how to access L1, for the purpose of resolving ENS,
  32. // for example.
  33. export class LayerOneConnectionPlugin extends NetworkPlugin {
  34. readonly provider!: Provider;
  35. // @TODO: Rename to ChainAccess and allow for connecting to any chain
  36. constructor(provider: Provider) {
  37. super("org.ethers.plugins.layer-one-connection");
  38. defineProperties<LayerOneConnectionPlugin>(this, { provider });
  39. }
  40. clone(): LayerOneConnectionPlugin {
  41. return new LayerOneConnectionPlugin(this.provider);
  42. }
  43. }
  44. */
  45. const Networks: Map<string | bigint, () => Network> = new Map();
  46. /**
  47. * A **Network** provides access to a chain's properties and allows
  48. * for plug-ins to extend functionality.
  49. */
  50. export class Network {
  51. #name: string;
  52. #chainId: bigint;
  53. #plugins: Map<string, NetworkPlugin>;
  54. /**
  55. * Creates a new **Network** for %%name%% and %%chainId%%.
  56. */
  57. constructor(name: string, chainId: BigNumberish) {
  58. this.#name = name;
  59. this.#chainId = getBigInt(chainId);
  60. this.#plugins = new Map();
  61. }
  62. /**
  63. * Returns a JSON-compatible representation of a Network.
  64. */
  65. toJSON(): any {
  66. return { name: this.name, chainId: String(this.chainId) };
  67. }
  68. /**
  69. * The network common name.
  70. *
  71. * This is the canonical name, as networks migh have multiple
  72. * names.
  73. */
  74. get name(): string { return this.#name; }
  75. set name(value: string) { this.#name = value; }
  76. /**
  77. * The network chain ID.
  78. */
  79. get chainId(): bigint { return this.#chainId; }
  80. set chainId(value: BigNumberish) { this.#chainId = getBigInt(value, "chainId"); }
  81. /**
  82. * Returns true if %%other%% matches this network. Any chain ID
  83. * must match, and if no chain ID is present, the name must match.
  84. *
  85. * This method does not currently check for additional properties,
  86. * such as ENS address or plug-in compatibility.
  87. */
  88. matches(other: Networkish): boolean {
  89. if (other == null) { return false; }
  90. if (typeof(other) === "string") {
  91. try {
  92. return (this.chainId === getBigInt(other));
  93. } catch (error) { }
  94. return (this.name === other);
  95. }
  96. if (typeof(other) === "number" || typeof(other) === "bigint") {
  97. try {
  98. return (this.chainId === getBigInt(other));
  99. } catch (error) { }
  100. return false;
  101. }
  102. if (typeof(other) === "object") {
  103. if (other.chainId != null) {
  104. try {
  105. return (this.chainId === getBigInt(other.chainId));
  106. } catch (error) { }
  107. return false;
  108. }
  109. if (other.name != null) {
  110. return (this.name === other.name);
  111. }
  112. return false;
  113. }
  114. return false;
  115. }
  116. /**
  117. * Returns the list of plugins currently attached to this Network.
  118. */
  119. get plugins(): Array<NetworkPlugin> {
  120. return Array.from(this.#plugins.values());
  121. }
  122. /**
  123. * Attach a new %%plugin%% to this Network. The network name
  124. * must be unique, excluding any fragment.
  125. */
  126. attachPlugin(plugin: NetworkPlugin): this {
  127. if (this.#plugins.get(plugin.name)) {
  128. throw new Error(`cannot replace existing plugin: ${ plugin.name } `);
  129. }
  130. this.#plugins.set(plugin.name, plugin.clone());
  131. return this;
  132. }
  133. /**
  134. * Return the plugin, if any, matching %%name%% exactly. Plugins
  135. * with fragments will not be returned unless %%name%% includes
  136. * a fragment.
  137. */
  138. getPlugin<T extends NetworkPlugin = NetworkPlugin>(name: string): null | T {
  139. return <T>(this.#plugins.get(name)) || null;
  140. }
  141. /**
  142. * Gets a list of all plugins that match %%name%%, with otr without
  143. * a fragment.
  144. */
  145. getPlugins<T extends NetworkPlugin = NetworkPlugin>(basename: string): Array<T> {
  146. return <Array<T>>(this.plugins.filter((p) => (p.name.split("#")[0] === basename)));
  147. }
  148. /**
  149. * Create a copy of this Network.
  150. */
  151. clone(): Network {
  152. const clone = new Network(this.name, this.chainId);
  153. this.plugins.forEach((plugin) => {
  154. clone.attachPlugin(plugin.clone());
  155. });
  156. return clone;
  157. }
  158. /**
  159. * Compute the intrinsic gas required for a transaction.
  160. *
  161. * A GasCostPlugin can be attached to override the default
  162. * values.
  163. */
  164. computeIntrinsicGas(tx: TransactionLike): number {
  165. const costs = this.getPlugin<GasCostPlugin>("org.ethers.plugins.network.GasCost") || (new GasCostPlugin());
  166. let gas = costs.txBase;
  167. if (tx.to == null) { gas += costs.txCreate; }
  168. if (tx.data) {
  169. for (let i = 2; i < tx.data.length; i += 2) {
  170. if (tx.data.substring(i, i + 2) === "00") {
  171. gas += costs.txDataZero;
  172. } else {
  173. gas += costs.txDataNonzero;
  174. }
  175. }
  176. }
  177. if (tx.accessList) {
  178. const accessList = accessListify(tx.accessList);
  179. for (const addr in accessList) {
  180. gas += costs.txAccessListAddress + costs.txAccessListStorageKey * accessList[addr].storageKeys.length;
  181. }
  182. }
  183. return gas;
  184. }
  185. /**
  186. * Returns a new Network for the %%network%% name or chainId.
  187. */
  188. static from(network?: Networkish): Network {
  189. injectCommonNetworks();
  190. // Default network
  191. if (network == null) { return Network.from("mainnet"); }
  192. // Canonical name or chain ID
  193. if (typeof(network) === "number") { network = BigInt(network); }
  194. if (typeof(network) === "string" || typeof(network) === "bigint") {
  195. const networkFunc = Networks.get(network);
  196. if (networkFunc) { return networkFunc(); }
  197. if (typeof(network) === "bigint") {
  198. return new Network("unknown", network);
  199. }
  200. assertArgument(false, "unknown network", "network", network);
  201. }
  202. // Clonable with network-like abilities
  203. if (typeof((<Network>network).clone) === "function") {
  204. const clone = (<Network>network).clone();
  205. //if (typeof(network.name) !== "string" || typeof(network.chainId) !== "number") {
  206. //}
  207. return clone;
  208. }
  209. // Networkish
  210. if (typeof(network) === "object") {
  211. assertArgument(typeof(network.name) === "string" && typeof(network.chainId) === "number",
  212. "invalid network object name or chainId", "network", network);
  213. const custom = new Network(<string>(network.name), <number>(network.chainId));
  214. if ((<any>network).ensAddress || (<any>network).ensNetwork != null) {
  215. custom.attachPlugin(new EnsPlugin((<any>network).ensAddress, (<any>network).ensNetwork));
  216. }
  217. //if ((<any>network).layerOneConnection) {
  218. // custom.attachPlugin(new LayerOneConnectionPlugin((<any>network).layerOneConnection));
  219. //}
  220. return custom;
  221. }
  222. assertArgument(false, "invalid network", "network", network);
  223. }
  224. /**
  225. * Register %%nameOrChainId%% with a function which returns
  226. * an instance of a Network representing that chain.
  227. */
  228. static register(nameOrChainId: string | number | bigint, networkFunc: () => Network): void {
  229. if (typeof(nameOrChainId) === "number") { nameOrChainId = BigInt(nameOrChainId); }
  230. const existing = Networks.get(nameOrChainId);
  231. if (existing) {
  232. assertArgument(false, `conflicting network for ${ JSON.stringify(existing.name) }`, "nameOrChainId", nameOrChainId);
  233. }
  234. Networks.set(nameOrChainId, networkFunc);
  235. }
  236. }
  237. type Options = {
  238. ensNetwork?: number;
  239. altNames?: Array<string>;
  240. plugins?: Array<NetworkPlugin>;
  241. };
  242. // We don't want to bring in formatUnits because it is backed by
  243. // FixedNumber and we want to keep Networks tiny. The values
  244. // included by the Gas Stations are also IEEE 754 with lots of
  245. // rounding issues and exceed the strict checks formatUnits has.
  246. function parseUnits(_value: number | string, decimals: number): bigint {
  247. const value = String(_value);
  248. if (!value.match(/^[0-9.]+$/)) {
  249. throw new Error(`invalid gwei value: ${ _value }`);
  250. }
  251. // Break into [ whole, fraction ]
  252. const comps = value.split(".");
  253. if (comps.length === 1) { comps.push(""); }
  254. // More than 1 decimal point or too many fractional positions
  255. if (comps.length !== 2) {
  256. throw new Error(`invalid gwei value: ${ _value }`);
  257. }
  258. // Pad the fraction to 9 decimalplaces
  259. while (comps[1].length < decimals) { comps[1] += "0"; }
  260. // Too many decimals and some non-zero ending, take the ceiling
  261. if (comps[1].length > 9) {
  262. let frac = BigInt(comps[1].substring(0, 9));
  263. if (!comps[1].substring(9).match(/^0+$/)) { frac++; }
  264. comps[1] = frac.toString();
  265. }
  266. return BigInt(comps[0] + comps[1]);
  267. }
  268. // Used by Polygon to use a gas station for fee data
  269. function getGasStationPlugin(url: string) {
  270. return new FetchUrlFeeDataNetworkPlugin(url, async (fetchFeeData, provider, request) => {
  271. // Prevent Cloudflare from blocking our request in node.js
  272. request.setHeader("User-Agent", "ethers");
  273. let response;
  274. try {
  275. const [ _response, _feeData ] = await Promise.all([
  276. request.send(), fetchFeeData()
  277. ]);
  278. response = _response;
  279. const payload = response.bodyJson.standard;
  280. const feeData = {
  281. gasPrice: _feeData.gasPrice,
  282. maxFeePerGas: parseUnits(payload.maxFee, 9),
  283. maxPriorityFeePerGas: parseUnits(payload.maxPriorityFee, 9),
  284. };
  285. return feeData;
  286. } catch (error: any) {
  287. assert(false, `error encountered with polygon gas station (${ JSON.stringify(request.url) })`, "SERVER_ERROR", { request, response, error });
  288. }
  289. });
  290. }
  291. // See: https://chainlist.org
  292. let injected = false;
  293. function injectCommonNetworks(): void {
  294. if (injected) { return; }
  295. injected = true;
  296. /// Register popular Ethereum networks
  297. function registerEth(name: string, chainId: number, options: Options): void {
  298. const func = function() {
  299. const network = new Network(name, chainId);
  300. // We use 0 to disable ENS
  301. if (options.ensNetwork != null) {
  302. network.attachPlugin(new EnsPlugin(null, options.ensNetwork));
  303. }
  304. network.attachPlugin(new GasCostPlugin());
  305. (options.plugins || []).forEach((plugin) => {
  306. network.attachPlugin(plugin);
  307. });
  308. return network;
  309. };
  310. // Register the network by name and chain ID
  311. Network.register(name, func);
  312. Network.register(chainId, func);
  313. if (options.altNames) {
  314. options.altNames.forEach((name) => {
  315. Network.register(name, func);
  316. });
  317. }
  318. }
  319. registerEth("mainnet", 1, { ensNetwork: 1, altNames: [ "homestead" ] });
  320. registerEth("ropsten", 3, { ensNetwork: 3 });
  321. registerEth("rinkeby", 4, { ensNetwork: 4 });
  322. registerEth("goerli", 5, { ensNetwork: 5 });
  323. registerEth("kovan", 42, { ensNetwork: 42 });
  324. registerEth("sepolia", 11155111, { ensNetwork: 11155111 });
  325. registerEth("holesky", 17000, { ensNetwork: 17000 });
  326. registerEth("classic", 61, { });
  327. registerEth("classicKotti", 6, { });
  328. registerEth("arbitrum", 42161, {
  329. ensNetwork: 1,
  330. });
  331. registerEth("arbitrum-goerli", 421613, { });
  332. registerEth("arbitrum-sepolia", 421614, { });
  333. registerEth("base", 8453, { ensNetwork: 1 });
  334. registerEth("base-goerli", 84531, { });
  335. registerEth("base-sepolia", 84532, { });
  336. registerEth("bnb", 56, { ensNetwork: 1 });
  337. registerEth("bnbt", 97, { });
  338. registerEth("linea", 59144, { ensNetwork: 1 });
  339. registerEth("linea-goerli", 59140, { });
  340. registerEth("linea-sepolia", 59141, { });
  341. registerEth("matic", 137, {
  342. ensNetwork: 1,
  343. plugins: [
  344. getGasStationPlugin("https:/\/gasstation.polygon.technology/v2")
  345. ]
  346. });
  347. registerEth("matic-amoy", 80002, { });
  348. registerEth("matic-mumbai", 80001, {
  349. altNames: [ "maticMumbai", "maticmum" ], // @TODO: Future remove these alts
  350. plugins: [
  351. getGasStationPlugin("https:/\/gasstation-testnet.polygon.technology/v2")
  352. ]
  353. });
  354. registerEth("optimism", 10, {
  355. ensNetwork: 1,
  356. plugins: [ ]
  357. });
  358. registerEth("optimism-goerli", 420, { });
  359. registerEth("optimism-sepolia", 11155420, { });
  360. registerEth("xdai", 100, { ensNetwork: 1 });
  361. }