network.js 13 KB

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