@hdwallet/core
Version:
A complete Hierarchical Deterministic (HD) Wallet generator for 200+ cryptocurrencies, built with TypeScript.
56 lines • 2.23 kB
JavaScript
// SPDX-License-Identifier: MIT
import { SLIP10Secp256k1PublicKey, validateAndGetPublicKey } from '../eccs';
import { Ethereum } from '../cryptocurrencies';
import { keccak256 } from '../crypto';
import { bytesToString } from '../utils';
import { AddressError } from '../exceptions';
import { Address } from './address';
export class EthereumAddress extends Address {
static addressPrefix = Ethereum.PARAMS.ADDRESS_PREFIX;
static getName() {
return 'Ethereum';
}
static checksumEncode(address) {
let output = '';
const addressHash = bytesToString(keccak256(new TextEncoder().encode(address.toLowerCase())));
for (let i = 0; i < address.length; i++) {
output += parseInt(addressHash[i], 16) >= 8
? address[i].toUpperCase()
: address[i];
}
return output;
}
static encode(publicKey, options = {
skipChecksumEncode: false
}) {
const pk = validateAndGetPublicKey(publicKey, SLIP10Secp256k1PublicKey);
const pubKeyHash = bytesToString(keccak256(pk.getRawUncompressed().slice(1))).slice(-40);
return this.addressPrefix + (options.skipChecksumEncode ? pubKeyHash : this.checksumEncode(pubKeyHash));
}
static decode(address, options = {
skipChecksumEncode: false
}) {
const prefix = address.slice(0, this.addressPrefix.length);
if (prefix !== this.addressPrefix) {
throw new AddressError('Invalid address prefix', {
expected: this.addressPrefix,
got: prefix
});
}
const addressPart = address.slice(this.addressPrefix.length);
if (addressPart.length !== 40) {
throw new AddressError('Invalid length', {
expected: 40,
got: addressPart.length
});
}
if (!options.skipChecksumEncode && addressPart !== this.checksumEncode(addressPart)) {
throw new AddressError('Invalid checksum encode', {
expected: this.checksumEncode(addressPart),
got: addressPart
});
}
return addressPart.toLowerCase();
}
}
//# sourceMappingURL=ethereum.js.map