Skip to content

Commit

Permalink
fix: rework deriveAddress to have all schemes support (#293)
Browse files Browse the repository at this point in the history
* fix: rework deriveAddress

* add extra copyright credit

* lint
  • Loading branch information
TarikGul authored May 3, 2023
1 parent c69ba73 commit 5b99d23
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
10 changes: 9 additions & 1 deletion packages/txwrapper-core/src/core/util/deriveAddress.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,20 @@ import { PolkadotSS58Format } from '@substrate/txwrapper-dev';
import { deriveAddress } from './deriveAddress';

describe('deriveAddress', () => {
it('should work', () => {
it('Should work for a Kusama sr25519 address', () => {
const address = deriveAddress(
'0x96074594cccf1cd185fa8a72ceaeefd86648f8d45514f3ce33c31bdd07e4655d',
PolkadotSS58Format.kusama
);

expect(address).toBe('Fy2rsYCoowQBtuFXqLE65ehAY9T6KWcGiNCQAyPDCkfpm4s');
});
it('Should work for a westend ecdsa address', () => {
const address = deriveAddress(
'0x02e59f872a5a49b7d4807f4f52db82c6d62ce11ba6ce1d13e490cb6cab302874fc',
PolkadotSS58Format.westend,
'ecdsa'
);
expect(address).toBe('5HpStbV2wnRhqiy8zsxeKYxJRLyKrsbH3Pyq9nrXtTeWXwcq');
});
});
30 changes: 27 additions & 3 deletions packages/txwrapper-core/src/core/util/deriveAddress.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,38 @@
import { encodeAddress } from '@polkadot/keyring';
import { Keyring } from '@polkadot/keyring';
import { hexToU8a, isHex } from '@polkadot/util';
import { blake2AsU8a } from '@polkadot/util-crypto';

/**
* Copyright 2023 via polkadot-js/common
*
* The slightly modified below logic is copyrighted from polkadot-js/common . The exact path to the code can be seen here:
* https://github.com/polkadot-js/common/blob/e5cb0ba2b4a6b5817626cc964b4f66334f2410e4/packages/keyring/src/pair/index.ts#L44-L49
*/
const TYPE_ADDRESS = {
ecdsa: (p: Uint8Array) => (p.length > 32 ? blake2AsU8a(p) : p),
ed25519: (p: Uint8Array) => p,
sr25519: (p: Uint8Array) => p,
};

/**
* Derive an address from a cryptographic public key offline.
*
* @param publicKey - The public key to derive from.
* @param ss58Format - The SS58 format to use.
* @param scheme - The scheme in which you want to apply. It defaults to sr25519
*/
export function deriveAddress(
publicKey: string | Uint8Array,
ss58Format: number
ss58Format: number,
scheme: 'ed25519' | 'sr25519' | 'ecdsa' = 'sr25519'
): string {
return encodeAddress(publicKey, ss58Format);
const raw = isHex(publicKey)
? hexToU8a(publicKey)
: (publicKey as Uint8Array);
const input = TYPE_ADDRESS[scheme](raw);

const keyring = new Keyring({ type: scheme, ss58Format: ss58Format });
const address = keyring.encodeAddress(input, ss58Format);

return address;
}

0 comments on commit 5b99d23

Please sign in to comment.