Skip to content

Commit

Permalink
round 1
Browse files Browse the repository at this point in the history
  • Loading branch information
alejoacosta74 committed May 17, 2024
1 parent 6eb0e4c commit 4da0a99
Show file tree
Hide file tree
Showing 5 changed files with 0 additions and 470 deletions.
109 changes: 0 additions & 109 deletions src.ts/hash/namehash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,112 +10,3 @@ import { ens_normalize } from "@adraffy/ens-normalize";
const Zeros = new Uint8Array(32);
Zeros.fill(0);

function checkComponent(comp: Uint8Array): Uint8Array {
assertArgument(comp.length !== 0, "invalid ENS name; empty component", "comp", comp)
return comp;
}

function ensNameSplit(name: string): Array<Uint8Array> {
const bytes = toUtf8Bytes(ensNormalize(name));
const comps: Array<Uint8Array> = [ ];

if (name.length === 0) { return comps; }

let last = 0;
for (let i = 0; i < bytes.length; i++) {
const d = bytes[i];

// A separator (i.e. "."); copy this component
if (d === 0x2e) {
comps.push(checkComponent(bytes.slice(last, i)));
last = i + 1;
}
}

// There was a stray separator at the end of the name
assertArgument(last < bytes.length, "invalid ENS name; empty component", "name", name);

comps.push(checkComponent(bytes.slice(last)));
return comps;
}

/**
* Returns the ENS `name` normalized.
*
* @param {string} name - The ENS name to normalize.
* @returns {string} The normalized ENS name.
*
* @category Hash
*/
export function ensNormalize(name: string): string {
try {
if (name.length === 0) { throw new Error("empty label"); }
return ens_normalize(name);
} catch (error: any) {
assertArgument(false, `invalid ENS name (${ error.message })`, "name", name);
}
}

/**
* Returns `true` if `name` is a valid ENS name.
*
* @param {string} name - The ENS name to validate.
* @returns {boolean} `true` if the name is valid.
*
* @category Hash
*/
export function isValidName(name: string): name is string {
try {
return (ensNameSplit(name).length !== 0);
} catch (error) { }
return false;
}

/**
* Returns the [namehash](https://docs.ens.domains/contract-api-reference/name-processing#hashing-names) for `name`.
*
* @param {string} name - The ENS name to hash.
* @returns {string} The namehash.
*
* @category Hash
*/
export function namehash(name: string): string {
assertArgument(typeof(name) === "string", "invalid ENS name; not a string", "name", name);

assertArgument(name.length, `invalid ENS name (empty label)`, "name", name);

let result: string | Uint8Array = Zeros;

const comps = ensNameSplit(name);
while (comps.length) {
result = keccak256(concat([ result, keccak256(<Uint8Array>(comps.pop()))] ));
}

return hexlify(result);
}

/**
* Returns the DNS encoded `name`.
*
* This is used for various parts of ENS name resolution, such
* as the wildcard resolution.
*
* @param {string} name - The ENS name to encode.
* @returns {string} The DNS encoded name.
*
* @category Hash
*/
export function dnsEncode(name: string): string {
return hexlify(concat(ensNameSplit(name).map((comp) => {
// DNS does not allow components over 63 bytes in length
if (comp.length > 63) {
throw new Error("invalid DNS encoded entry; length exceeds 63 bytes");
}

const bytes = new Uint8Array(comp.length + 1);
bytes.set(comp, 1);
bytes[0] = bytes.length - 1;
return bytes;

}))) + "00";
}
270 changes: 0 additions & 270 deletions src.ts/providers/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,25 +33,6 @@ export type Networkish = Network | number | bigint | string | {
ensNetwork?: number
};

/* * * *
// Networks which operation against an L2 can use this plugin to
// specify how to access L1, for the purpose of resolving ENS,
// for example.
export class LayerOneConnectionPlugin extends NetworkPlugin {
readonly provider!: Provider;
// @TODO: Rename to ChainAccess and allow for connecting to any chain
constructor(provider: Provider) {
super("org.quais.plugins.layer-one-connection");
defineProperties<LayerOneConnectionPlugin>(this, { provider });
}
clone(): LayerOneConnectionPlugin {
return new LayerOneConnectionPlugin(this.provider);
}
}
*/


const Networks: Map<string | bigint, () => Network> = new Map();


Expand Down Expand Up @@ -197,254 +178,3 @@ export class Network {
return clone;
}

/**
* Compute the intrinsic gas required for a transaction.
*
* A GasCostPlugin can be attached to override the default
* values.
*/
// computeIntrinsicGas(tx: TransactionLike): number {
// const costs = this.getPlugin<GasCostPlugin>("org.quais.plugins.network.GasCost") || (new GasCostPlugin());
//
// let gas = costs.txBase;
// if (tx.to == null) { gas += costs.txCreate; }
// if (tx.data) {
// for (let i = 2; i < tx.data.length; i += 2) {
// if (tx.data.substring(i, i + 2) === "00") {
// gas += costs.txDataZero;
// } else {
// gas += costs.txDataNonzero;
// }
// }
// }
//
// if (tx.accessList) {
// const accessList = accessListify(tx.accessList);
// for (const addr in accessList) {
// gas += costs.txAccessListAddress + costs.txAccessListStorageKey * accessList[addr].storageKeys.length;
// }
// }
//
// return gas;
// }

/**
* Returns a new Network for the `network` name or chainId.
*
* @param {Networkish} network - The network to get.
* @returns {Network} The Network instance.
*/
static from(network?: Networkish): Network {
injectCommonNetworks();

// Default network
if (network == null) { return Network.from("mainnet"); }

// Canonical name or chain ID
if (typeof(network) === "number") { network = BigInt(network); }
if (typeof(network) === "string" || typeof(network) === "bigint") {
const networkFunc = Networks.get(network);
if (networkFunc) { return networkFunc(); }
if (typeof(network) === "bigint") {
return new Network("unknown", network);
}

assertArgument(false, "unknown network", "network", network);
}

// Clonable with network-like abilities
if (typeof((<Network>network).clone) === "function") {
const clone = (<Network>network).clone();
//if (typeof(network.name) !== "string" || typeof(network.chainId) !== "number") {
//}
return clone;
}

// Networkish
if (typeof(network) === "object") {
assertArgument(typeof(network.name) === "string" && typeof(network.chainId) === "number",
"invalid network object name or chainId", "network", network);

const custom = new Network(<string>(network.name), <number>(network.chainId));

if ((<any>network).ensAddress || (<any>network).ensNetwork != null) {
custom.attachPlugin(new EnsPlugin((<any>network).ensAddress, (<any>network).ensNetwork));
}

//if ((<any>network).layerOneConnection) {
// custom.attachPlugin(new LayerOneConnectionPlugin((<any>network).layerOneConnection));
//}

return custom;
}

assertArgument(false, "invalid network", "network", network);
}

/**
* Register `nameOrChainId` with a function which returns
* an instance of a Network representing that chain.
*
* @param {string | number | bigint} nameOrChainId - The name or chain ID to register.
* @param {() => Network} networkFunc - The function to create the Network.
* @throws If a network is already registered for `nameOrChainId`.
*/
static register(nameOrChainId: string | number | bigint, networkFunc: () => Network): void {
if (typeof(nameOrChainId) === "number") { nameOrChainId = BigInt(nameOrChainId); }
const existing = Networks.get(nameOrChainId);
if (existing) {
assertArgument(false, `conflicting network for ${ JSON.stringify(existing.name) }`, "nameOrChainId", nameOrChainId);
}
Networks.set(nameOrChainId, networkFunc);
}
}


type Options = {
ensNetwork?: number;
altNames?: Array<string>;
plugins?: Array<NetworkPlugin>;
};

// We don't want to bring in formatUnits because it is backed by
// FixedNumber and we want to keep Networks tiny. The values
// included by the Gas Stations are also IEEE 754 with lots of
// rounding issues and exceed the strict checks formatUnits has.
function parseUnits(_value: number | string, decimals: number): bigint {
const value = String(_value);
if (!value.match(/^[0-9.]+$/)) {
throw new Error(`invalid gwei value: ${ _value }`);
}

// Break into [ whole, fraction ]
const comps = value.split(".");
if (comps.length === 1) { comps.push(""); }

// More than 1 decimal point or too many fractional positions
if (comps.length !== 2) {
throw new Error(`invalid gwei value: ${ _value }`);
}

// Pad the fraction to 9 decimalplaces
while (comps[1].length < decimals) { comps[1] += "0"; }

// Too many decimals and some non-zero ending, take the ceiling
if (comps[1].length > 9) {
let frac = BigInt(comps[1].substring(0, 9));
if (!comps[1].substring(9).match(/^0+$/)) { frac++; }
comps[1] = frac.toString();
}

return BigInt(comps[0] + comps[1]);
}

// Used by Polygon to use a gas station for fee data
function getGasStationPlugin(url: string) {
return new FetchUrlFeeDataNetworkPlugin(url, async (fetchFeeData, provider, request) => {

// Prevent Cloudflare from blocking our request in node.js
request.setHeader("User-Agent", "quais");

let response;
try {
const [ _response, _feeData ] = await Promise.all([
request.send(), fetchFeeData()
]);
response = _response;
const payload = response.bodyJson.standard;
const feeData = {
gasPrice: _feeData.gasPrice,
maxFeePerGas: parseUnits(payload.maxFee, 9),
maxPriorityFeePerGas: parseUnits(payload.maxPriorityFee, 9),
};
return feeData;
} catch (error: any) {
assert(false, `error encountered with polygon gas station (${ JSON.stringify(request.url) })`, "SERVER_ERROR", { request, response, error });
}
});
}

// See: https://chainlist.org
let injected = false;
function injectCommonNetworks(): void {
if (injected) { return; }
injected = true;

/// Register popular Ethereum networks
function registerEth(name: string, chainId: number, options: Options): void {
const func = function() {
const network = new Network(name, chainId);

// We use 0 to disable ENS
if (options.ensNetwork != null) {
network.attachPlugin(new EnsPlugin(null, options.ensNetwork));
}

network.attachPlugin(new GasCostPlugin());

(options.plugins || []).forEach((plugin) => {
network.attachPlugin(plugin);
});

return network;
};

// Register the network by name and chain ID
Network.register(name, func);
Network.register(chainId, func);

if (options.altNames) {
options.altNames.forEach((name) => {
Network.register(name, func);
});
}
}

registerEth("mainnet", 1, { ensNetwork: 1, altNames: [ "homestead" ] });
registerEth("ropsten", 3, { ensNetwork: 3 });
registerEth("rinkeby", 4, { ensNetwork: 4 });
registerEth("goerli", 5, { ensNetwork: 5 });
registerEth("kovan", 42, { ensNetwork: 42 });
registerEth("sepolia", 11155111, { ensNetwork: 11155111 });



registerEth("classic", 61, { });
registerEth("classicKotti", 6, { });

registerEth("arbitrum", 42161, {
ensNetwork: 1,
});
registerEth("arbitrum-goerli", 421613, { });

registerEth("base", 8453, { ensNetwork: 1 });
registerEth("base-goerli", 84531, { });
registerEth("base-sepolia", 84532, { });

registerEth("bnb", 56, { ensNetwork: 1 });
registerEth("bnbt", 97, { });

registerEth("linea", 59144, { ensNetwork: 1 });
registerEth("linea-goerli", 59140, { });

registerEth("matic", 137, {
ensNetwork: 1,
plugins: [
getGasStationPlugin("https:/\/gasstation.polygon.technology/v2")
]
});
registerEth("matic-mumbai", 80001, {
altNames: [ "maticMumbai", "maticmum" ], // @TODO: Future remove these alts
plugins: [
getGasStationPlugin("https:/\/gasstation-testnet.polygon.technology/v2")
]
});

registerEth("optimism", 10, {
ensNetwork: 1,
plugins: [ ]
});
registerEth("optimism-goerli", 420, { });

registerEth("xdai", 100, { ensNetwork: 1 });
}
Loading

0 comments on commit 4da0a99

Please sign in to comment.