network.js 13 KB

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