feat: add createProgramAddress

This commit is contained in:
Jack May 2020-05-26 17:46:49 -07:00 committed by Michael Vines
parent 85c68bc953
commit a29e088169
2 changed files with 59 additions and 1 deletions

View File

@ -78,7 +78,7 @@ export class PublicKey {
}
/**
* Derive a public key from another key, a seed, and a programId.
* Derive a public key from another key, a seed, and a program ID.
*/
static async createWithSeed(
fromPublicKey: PublicKey,
@ -93,4 +93,25 @@ export class PublicKey {
const hash = await sha256(new Uint8Array(buffer));
return new PublicKey('0x' + hash);
}
/**
* Derive a program address from seeds and a program ID.
*/
static async createProgramAddress(
seeds: Array<string>,
programId: PublicKey,
): Promise<PublicKey> {
let buffer = Buffer.alloc(0);
seeds.forEach(function (seed) {
buffer = Buffer.concat([buffer, Buffer.from(seed)]);
});
buffer = Buffer.concat([
buffer,
programId.toBuffer(),
Buffer.from('ProgramDerivedAddress'),
]);
let hash = await sha256(new Uint8Array(buffer));
hash = await sha256(new Uint8Array(new BN(hash, 16).toBuffer()));
return new PublicKey('0x' + hash);
}
}

View File

@ -238,3 +238,40 @@ test('createWithSeed', async () => {
),
).toBe(true);
});
test('createProgramAddress', async () => {
const programId = new PublicKey(
'BPFLoader1111111111111111111111111111111111',
);
let programAddress = await PublicKey.createProgramAddress([''], programId);
expect(
programAddress.equals(
new PublicKey('CsdSsqp6Upkh2qajhZMBM8xT4GAyDNSmcV37g4pN8rsc'),
),
).toBe(true);
programAddress = await PublicKey.createProgramAddress(['☉'], programId);
expect(
programAddress.equals(
new PublicKey('A8mYnN8Pfx7Nn6f8RoQgsPNtAGAWmmKSBCDfyDvE6sXF'),
),
).toBe(true);
programAddress = await PublicKey.createProgramAddress(
['Talking', 'Squirrels'],
programId,
);
expect(
programAddress.equals(
new PublicKey('CawYq8Rmj4JRR992wVnGEFUjMEkmtmcFgEL4iS1qPczu'),
),
).toBe(true);
programAddress = await PublicKey.createProgramAddress(
['Talking', 'Squirrels'],
programId,
);
const programAddress2 = await PublicKey.createProgramAddress(
['Talking'],
programId,
);
expect(programAddress.equals(programAddress2)).toBe(false);
});