Skip to content

Commit

Permalink
fix: remove async for createProgramAddress and findProgramAddress (so…
Browse files Browse the repository at this point in the history
  • Loading branch information
yangli-io committed Feb 17, 2022
1 parent 7939fdc commit f476158
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
33 changes: 28 additions & 5 deletions web3.js/src/publickey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,10 @@ export class PublicKey extends Struct {
* Derive a program address from seeds and a program ID.
*/
/* eslint-disable require-await */
static async createProgramAddress(
static createProgramAddressSync(
seeds: Array<Buffer | Uint8Array>,
programId: PublicKey,
): Promise<PublicKey> {
): PublicKey {
let buffer = Buffer.alloc(0);
seeds.forEach(function (seed) {
if (seed.length > MAX_SEED_LENGTH) {
Expand All @@ -167,23 +167,35 @@ export class PublicKey extends Struct {
return new PublicKey(publicKeyBytes);
}

/**
* Async version of createProgramAddressSync
* For backwards compatibility
*/
/* eslint-disable require-await */
static async createProgramAddress(
seeds: Array<Buffer | Uint8Array>,
programId: PublicKey,
): Promise<PublicKey> {
return this.createProgramAddressSync(seeds, programId);
}

/**
* Find a valid program address
*
* Valid program addresses must fall off the ed25519 curve. This function
* iterates a nonce until it finds one that when combined with the seeds
* results in a valid program address.
*/
static async findProgramAddress(
static findProgramAddressSync(
seeds: Array<Buffer | Uint8Array>,
programId: PublicKey,
): Promise<[PublicKey, number]> {
): [PublicKey, number] {
let nonce = 255;
let address;
while (nonce != 0) {
try {
const seedsWithNonce = seeds.concat(Buffer.from([nonce]));
address = await this.createProgramAddress(seedsWithNonce, programId);
address = this.createProgramAddressSync(seedsWithNonce, programId);
} catch (err) {
if (err instanceof TypeError) {
throw err;
Expand All @@ -196,6 +208,17 @@ export class PublicKey extends Struct {
throw new Error(`Unable to find a viable program address nonce`);
}

/**
* Async version of findProgramAddressSync
* For backwards compatibility
*/
static async findProgramAddress(
seeds: Array<Buffer | Uint8Array>,
programId: PublicKey,
): Promise<[PublicKey, number]> {
return this.findProgramAddressSync(seeds, programId);
}

/**
* Check that a pubkey is on the ed25519 curve.
*/
Expand Down
2 changes: 1 addition & 1 deletion web3.js/test/publickey.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,4 +246,4 @@ describe('PublicKey', function () {
const decoded = PublicKey.decodeUnchecked(encoded);
expect(decoded.equals(publicKey)).to.be.true;
});
});
});

0 comments on commit f476158

Please sign in to comment.