@polkadot/util-crypto#decodeAddress TypeScript Examples
The following examples show how to use
@polkadot/util-crypto#decodeAddress.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts From evm-provider.js with Apache License 2.0 | 7 votes |
export function createClaimEvmSignature(substrateAddress: string): Bytes {
const publicKeySubstrate = decodeAddress(substrateAddress);
let message: Bytes | string =
'reef evm:' + Buffer.from(publicKeySubstrate).toString('hex');
if (typeof message === 'string') {
message = toUtf8Bytes(message);
}
return message;
}
Example #2
Source File: Signer.ts From bodhi.js with Apache License 2.0 | 6 votes |
async claimEvmAccount(evmAddress: string): Promise<void> {
const isConnented = await this.isClaimed(evmAddress);
if (isConnented) return;
const publicKey = decodeAddress(this._substrateAddress);
const data = 'acala evm:' + Buffer.from(publicKey).toString('hex');
const signature = await this._signMessage(evmAddress, data);
const extrinsic = this.provider.api.tx.evmAccounts.claimAccount(evmAddress, signature);
await extrinsic.signAsync(this._substrateAddress);
await new Promise<void>((resolve, reject) => {
extrinsic
.send((result: SubmittableResult) => {
handleTxResponse(result, this.provider.api)
.then(() => {
resolve();
})
.catch((err) => {
if (err.message === 'evmAccounts.AccountIdHasMapped') {
resolve();
}
reject(err);
});
})
.catch(reject);
});
}
Example #3
Source File: address.ts From subscan-multisig-react with Apache License 2.0 | 6 votes |
export function convertToEth(address: string): string | null {
if (!address) {
return '';
}
const startAt = 2;
const result = u8aToHex(decodeAddress(address)).slice(startAt);
const PREFIX = '64766d3a00000000000000';
// eslint-disable-next-line no-magic-numbers
return result.startsWith(PREFIX) ? '0x' + result.slice(-42, -2) : null;
}
Example #4
Source File: BaseBytes.tsx From subscan-multisig-react with Apache License 2.0 | 6 votes |
function convertInput(value: string): [boolean, Uint8Array] {
if (value === '0x') {
return [true, new Uint8Array([])];
} else if (value.startsWith('0x')) {
try {
return [true, hexToU8a(value)];
} catch (error) {
return [false, new Uint8Array([])];
}
}
// maybe it is an ss58?
try {
return [true, decodeAddress(value)];
} catch (error) {
// we continue
}
return isAscii(value) ? [true, stringToU8a(value)] : [value === '0x', new Uint8Array([])];
}
Example #5
Source File: useAccounts.ts From subscan-multisig-react with Apache License 2.0 | 6 votes |
export function useAccounts(): UseAccounts {
const mountedRef = useIsMountedRef();
const [state, setState] = useState<UseAccounts>(EMPTY);
useEffect((): (() => void) => {
const subscription = keyring.accounts.subject.subscribe((accounts): void => {
if (mountedRef.current) {
const allAccounts = accounts ? Object.keys(accounts) : [];
const allAccountsHex = allAccounts.map((a) => u8aToHex(decodeAddress(a)));
const hasAccounts = allAccounts.length !== 0;
const isAccount = (address?: string | null) => !!address && allAccounts.includes(address);
setState({ allAccounts, allAccountsHex, areAccountsLoaded: true, hasAccounts, isAccount });
}
});
return (): void => {
setTimeout(() => subscription.unsubscribe(), 0);
};
}, [mountedRef]);
return state;
}
Example #6
Source File: index.spec.ts From evm-provider.js with Apache License 2.0 | 6 votes |
describe('evm-provider', () => {
it('should export the Provider', () => {
expect(Provider).toBeDefined();
});
it('default evm address', () => {
const accountid = decodeAddress(
'5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY'
);
const encode = u8aConcat('evm:', accountid);
expect(u8aToHex(blake2AsU8a(encode, 256).slice(0, 20))).toEqual(
'0xf4ca11ca834c9e2fb49f059ab71fb9c72dad05f9'
);
});
});
Example #7
Source File: Signer.ts From evm-provider.js with Apache License 2.0 | 6 votes |
constructor(provider: Provider, address: string, signingKey: SigningKey) {
super();
defineReadOnly(this, 'provider', provider);
defineReadOnly(this, 'signingKey', signingKey);
// @ts-ignore
this.provider.api.setSigner(signingKey);
if (typeof address === 'string' && isEthereumAddress(address)) {
logger.throwError('expect substrate address');
} else {
try {
decodeAddress(address);
defineReadOnly(this, '_substrateAddress', address);
} catch {
logger.throwArgumentError('invalid address', 'address', address);
}
}
}
Example #8
Source File: Signer.ts From evm-provider.js with Apache License 2.0 | 6 votes |
async claimEvmAccount(evmAddress: string): Promise<void> {
const isConnented = await this.isClaimed(evmAddress);
if (isConnented) return;
const publicKey = decodeAddress(this._substrateAddress);
const data = 'Reef evm:' + Buffer.from(publicKey).toString('hex');
const signature = await this._signMessage(evmAddress, data);
const extrinsic = this.provider.api.tx.evmAccounts.claimAccount(
evmAddress,
signature
);
await extrinsic.signAsync(this._substrateAddress);
await new Promise<void>((resolve, reject) => {
extrinsic
.send((result: SubmittableResult) => {
handleTxResponse(result, this.provider.api)
.then(() => {
resolve();
})
.catch(({ message, result }) => {
if (message === 'evmAccounts.AccountIdHasMapped') {
resolve();
}
reject(message);
});
})
.catch((error) => {
reject(error && error.message);
});
});
}
Example #9
Source File: Signer.ts From evm-provider.js with Apache License 2.0 | 6 votes |
/**
*
* @returns The default EVM address generated for the signer's substrate address
*/
computeDefaultEvmAddress(): string {
const address = this._substrateAddress;
const publicKey = decodeAddress(address);
const isStartWithEvm = u8aEq('evm:', publicKey.slice(0, 4));
if (isStartWithEvm) {
return getAddress(u8aToHex(publicKey.slice(4, 24)));
}
return getAddress(
u8aToHex(blake2AsU8a(u8aConcat('evm:', publicKey), 256).slice(0, 20))
);
}
Example #10
Source File: bundle.ts From phishing with Apache License 2.0 | 6 votes |
/**
* Determines if a host is in our deny list. Returns a string containing the phishing site if host is a
* problematic one. Returns null if the address is not associated with phishing.
*/
export async function checkAddress (address: string | Uint8Array, allowCached = true): Promise<string | null> {
try {
const u8a = decodeAddress(address);
const all = await retrieveAddrU8a(allowCached);
const entry = all.find(([, all]) => all.some((a) => u8aEq(a, u8a))) || [null];
return entry[0];
} catch (error) {
log(error, 'address');
return null;
}
}
Example #11
Source File: bundle.ts From phishing with Apache License 2.0 | 6 votes |
/**
* Retrieve a list of known phishing addresses in raw Uint8Array format
*/
async function retrieveAddrU8a (allowCached = true): Promise<[string, Uint8Array[]][]> {
const now = Date.now();
return (allowCached && cacheAddrU8a && (now < cacheAddrEnd))
? cacheAddrU8a
: retrieveAddrList(allowCached).then((all) => {
cacheAddrU8a = Object
.entries(all)
.map(([key, addresses]): [string, Uint8Array[]] =>
[key, addresses.map((a) => decodeAddress(a))]
);
return cacheAddrU8a;
});
}
Example #12
Source File: additions.spec.ts From phishing with Apache License 2.0 | 6 votes |
describe('added addresses', (): void => {
it('has no malformed addresses', (): void => {
const invalids = Object
.entries(addresses)
.map(([url, addrs]): [string, string[]] => {
return [url, addrs.filter((a) => {
try {
return decodeAddress(a).length !== 32;
} catch (error) {
console.error(url, (error as Error).message);
return true;
}
})];
})
.filter(([, addrs]) => addrs.length);
if (invalids.length) {
throw new Error(`Invalid ss58 checksum addresses found: ${invalids.map(([url, addrs]) => `\n\t${url}: ${addrs.join(', ')}`).join('')}`);
}
});
it('has no entries on the known addresses list', (): void => {
const added = Object
.values(addresses)
.reduce<string[]>((all, addrs) => all.concat(addrs), []);
const dupes = Object
.entries(allowed)
.reduce<[string, string][]>((all, [site, addrs]) => all.concat(addrs.map((a) => [site, a])), [])
.filter(([, a]) => added.includes(a));
expect(dupes).toEqual([]);
});
});
Example #13
Source File: index.ts From parachain-launch with Apache License 2.0 | 6 votes |
getAddress = (val: string) => {
try {
const addr = decodeAddress(val);
return encodeAddress(addr);
} catch {}
const keyring = new Keyring();
const pair = keyring.createFromUri(`//${_.startCase(val)}`, undefined, 'sr25519');
return pair.address;
}
Example #14
Source File: addressSwapper.ts From commonwealth with GNU General Public License v3.0 | 6 votes |
AddressSwapper = (options) => {
if (!options.address) throw new Error('No address provided to swap');
if (!options.currentPrefix) return options.address;
if (isU8a(options.address) || isHex(options.address)) {
throw new Error('address not in SS58 format');
}
// check if it is valid as an address
let decodedAddress: Uint8Array;
try {
decodedAddress = decodeAddress(options.address);
} catch (e) {
throw new Error('failed to decode address');
}
// check if it is valid with the current prefix & reencode if needed
const [valid, errorMsg] = checkAddress(options.address, options.currentPrefix);
if (!valid) {
try {
return encodeAddress(decodedAddress, options.currentPrefix);
} catch (e) {
throw new Error('failed to reencode address');
}
} else {
return options.address;
}
}
Example #15
Source File: address_swapper.ts From commonwealth with GNU General Public License v3.0 | 6 votes |
AddressSwapper = (options: {
address: string, currentPrefix: number,
}): string => {
if (!options.address) throw new Error('No address provided to swap');
if (!options.currentPrefix) return options.address;
if (isU8a(options.address) || isHex(options.address)) {
throw new Error('address not in SS58 format');
}
// check if it is valid as an address
let decodedAddress: Uint8Array;
try {
decodedAddress = decodeAddress(options.address);
} catch (e) {
throw new Error('failed to decode address');
}
// check if it is valid with the current prefix & reencode if needed
const [valid, errorMsg] = checkAddress(options.address, options.currentPrefix);
if (!valid) {
try {
return encodeAddress(decodedAddress, options.currentPrefix);
} catch (e) {
throw new Error('failed to reencode address');
}
} else {
return options.address;
}
}
Example #16
Source File: BaseBytes.tsx From crust-apps with Apache License 2.0 | 6 votes |
function convertInput (value: string): [boolean, Uint8Array] {
if (value === '0x') {
return [true, new Uint8Array([])];
} else if (value.startsWith('0x')) {
try {
return [true, hexToU8a(value)];
} catch (error) {
return [false, new Uint8Array([])];
}
}
// maybe it is an ss58?
try {
return [true, decodeAddress(value)];
} catch (error) {
// we continue
}
return isAscii(value)
? [true, stringToU8a(value)]
: [value === '0x', new Uint8Array([])];
}
Example #17
Source File: Signer.ts From bodhi.js with Apache License 2.0 | 6 votes |
/**
*
* @returns The default EVM address generated for the signer's substrate address
*/
computeDefaultEvmAddress(): string {
const address = this._substrateAddress;
const publicKey = decodeAddress(address);
const isStartWithEvm = u8aEq('evm:', publicKey.slice(0, 4));
if (isStartWithEvm) {
return getAddress(u8aToHex(publicKey.slice(4, 24)));
}
return getAddress(u8aToHex(blake2AsU8a(u8aConcat('evm:', publicKey), 256).slice(0, 20)));
}
Example #18
Source File: Signer.ts From bodhi.js with Apache License 2.0 | 6 votes |
constructor(provider: SignerProvider, address: string, signingKey: SigningKey) {
super();
defineReadOnly(this, 'provider', provider);
defineReadOnly(this, 'signingKey', signingKey);
// @ts-ignore
this.provider.api.setSigner(signingKey);
if (typeof address === 'string' && isEthereumAddress(address)) {
logger.throwError('expect substrate address');
} else {
try {
decodeAddress(address);
defineReadOnly(this, '_substrateAddress', address);
} catch {
logger.throwArgumentError('invalid address', 'address', address);
}
}
}
Example #19
Source File: index.test.ts From bodhi.js with Apache License 2.0 | 6 votes |
describe('bodhi', () => {
it('should export the Provider', () => {
expect(Provider).to.not.be.undefined;
});
it('default evm address', () => {
const accountid = decodeAddress('5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY');
const encode = u8aConcat('evm:', accountid);
expect(u8aToHex(blake2AsU8a(encode, 256).slice(0, 20))).to.equal('0xf4ca11ca834c9e2fb49f059ab71fb9c72dad05f9');
});
});
Example #20
Source File: address.ts From bodhi.js with Apache License 2.0 | 6 votes |
computeDefaultEvmAddress = (substrateAddress: HexString | string | Uint8Array): string => {
if (!isSubstrateAddress) {
return logger.throwArgumentError('invalid substrate address', 'address', substrateAddress);
}
const publicKey = decodeAddress(substrateAddress);
const isStartWithEvm = u8aEq('evm:', publicKey.slice(0, 4));
if (isStartWithEvm) {
return getAddress(u8aToHex(publicKey.slice(4, 24)));
}
return getAddress(u8aToHex(blake2AsU8a(u8aConcat('evm:', publicKey), 256).slice(0, 20)));
}
Example #21
Source File: utils.ts From atlas with GNU General Public License v3.0 | 6 votes |
addressToId = (address: string) => {
return blake2(decodeAddress(address)).map((x, i): number => (x + 256 - ZERO[i]) % 256)
}
Example #22
Source File: validation.ts From community-repo with GNU General Public License v3.0 | 6 votes |
export function validateAddress(
address: string,
errorMessage = 'Invalid address'
): void {
try {
decodeAddress(address);
} catch (e) {
throw new Error(errorMessage);
}
}
Example #23
Source File: getDeriveAccount.ts From parity-bridges-ui with GNU General Public License v3.0 | 5 votes |
export default function getDeriveAccount({ ss58Format = 42, bridgeId, address }: Data): string {
if (!address) {
return address;
}
const input = [...compactAddLength(stringToU8a(accountDerivation)), ...bridgeId, ...decodeAddress(address)];
return encodeAddress(blake2AsHex(Uint8Array.from(input)), ss58Format);
}
Example #24
Source File: addrcheck.spec.ts From phishing with Apache License 2.0 | 5 votes |
describe('addrcheck', (): void => {
beforeAll((): void => {
jest.setTimeout(2 * 60 * 1000);
});
it('has all known addresses', async (): Promise<void> => {
const _results = await checkAll();
const results = _results.map(([url, addrs]): [string, string[]] => {
return [url, addrs.filter((a) => {
try {
return decodeAddress(a).length === 32;
} catch (error) {
console.error(url, (error as Error).message);
return false;
}
})];
});
const all = Object.values(ourAddrList).reduce((all: string[], addrs: string[]): string[] => {
all.push(...addrs);
return all;
}, []);
const listEmpty = results.filter(([, found]) => !found.length).map(([site]) => site);
const mapFound = results.filter(([, found]) => found.length).reduce((all, [site, found]) => ({ ...all, [site]: found }), {});
const mapMiss = results
.map(([site, found]): [string, string[]] => [site, found.filter((a) => !all.includes(a))])
.filter(([, found]) => found.length)
.reduce((all: Record<string, string[]>, [site, found]) => ({
...all,
[site]: (all[site] || []).concat(found)
}), {});
const sites = Object.keys(mapMiss);
console.log('Sites with no results\n', JSON.stringify(listEmpty, null, 2));
console.log('Addresses found\n', JSON.stringify(mapFound, null, 2));
console.log('Addresses missing\n', JSON.stringify(mapMiss, null, 2));
sites.length && process.env.CI_LOG && fs.appendFileSync('./.github/addrcheck.md', `\n\n${sites.length} urls with missing entries found at ${new Date().toUTCString()}:\n\n${TICKS}\n${JSON.stringify(mapMiss, null, 2)}\n${TICKS}\n`);
expect(sites).toEqual([]);
});
});
Example #25
Source File: QrSigner.ts From sdk with Apache License 2.0 | 5 votes |
function _createSignPayload(address: string, cmd: number, payload: Uint8Array | any, genesisHash: Uint8Array | any) {
return u8aConcat(SUBSTRATE_ID, CRYPTO_SR25519, new Uint8Array([cmd]), decodeAddress(address), u8aToU8a(payload), u8aToU8a(genesisHash));
}
Example #26
Source File: createClaimPayload.ts From bodhi.js with Apache License 2.0 | 5 votes |
createClaimPayload = (tx: ClaimPayload) => {
if (!tx.salt) {
return logger.throwError('claim payload missing salt');
}
if (!tx.chainId) {
return logger.throwError('claim payload missing chainId');
}
if (!tx.substrateAddress) {
return logger.throwError('claim payload missing substrateAddress');
}
let publicKey: Uint8Array;
try {
publicKey = decodeAddress(tx.substrateAddress);
} catch {
return logger.throwError('invalid substrateAddress');
}
return {
types: {
EIP712Domain: [
{
name: 'name',
type: 'string'
},
{
name: 'version',
type: 'string'
},
{
name: 'chainId',
type: 'uint256'
},
{
name: 'salt',
type: 'bytes32'
}
],
Transaction: [{ name: 'substrateAddress', type: 'bytes' }]
},
primaryType: 'Transaction' as const,
domain: {
name: 'Acala EVM claim',
version: '1',
chainId: tx.chainId,
salt: hexlify(tx.salt)
},
message: {
substrateAddress: hexlify(publicKey)
}
};
}
Example #27
Source File: address.ts From bodhi.js with Apache License 2.0 | 5 votes |
isSubstrateAddress = (address: HexString | string | Uint8Array) => {
try {
decodeAddress(address);
return true;
} catch {
return false;
}
}
Example #28
Source File: address.ts From subscan-multisig-react with Apache License 2.0 | 5 votes |
export function convertToDvm(address: string): string {
if (!address) {
return '';
}
return u8aToHex(decodeAddress(address));
}
Example #29
Source File: accounts.ts From subsocial-js with GNU General Public License v3.0 | 5 votes |
toSubsocialAddress = (address?: string) => {
if (!address || !isAddress(address)) return undefined
return encodeAddress(decodeAddress(address), 28)
}