This repository has been archived by the owner on Mar 29, 2023. It is now read-only.
/
utils.ts
87 lines (73 loc) · 2.24 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { JsonFragment } from '@ethersproject/abi';
import { PublicKey } from '@solana/web3.js';
import { randomBytes } from 'crypto';
/** Application Binary Interface of a Solidity contract in JSON form */
export type ABI = JsonFragment[];
/** PDA and the seed used to derive it */
export interface ProgramDerivedAddress {
address: PublicKey;
seed: Buffer;
}
/**
* Create a Program Derived Address from a program ID and a random seed
*
* @param program Program ID to derive the PDA using
*
* @return PDA and the seed used to derive it
*/
export async function createProgramDerivedAddress(program: PublicKey): Promise<ProgramDerivedAddress> {
// eslint-disable-next-line no-constant-condition
while (true) {
const seed = randomBytes(7);
let address: PublicKey;
try {
address = await PublicKey.createProgramAddress([seed], program);
} catch (error) {
// If a valid PDA can't be found using the seed, generate another and try again
continue;
}
return { address, seed };
}
}
/**
* Encode a public key as a hexadecimal string
*
* @param publicKey Public key to convert
*
* @return Hex-encoded public key
*/
export function publicKeyToHex(publicKey: PublicKey): string {
return '0x' + publicKey.toBuffer().toString('hex');
}
/** @internal */
export type Seed = string | PublicKey | Uint8Array | Buffer;
/** @internal */
export function seedToBuffer(seed: Seed): Buffer {
if (seed instanceof Buffer) {
return seed;
} else if (typeof seed === 'string') {
return Buffer.from(seed, 'utf-8');
} else if (seed instanceof PublicKey) {
return seed.toBuffer();
} else {
return Buffer.from(seed);
}
}
/** @internal */
export function encodeSeeds(seeds: Seed[]): Buffer {
const buffers = seeds.map(seedToBuffer);
let length = 1;
for (const buffer of buffers) {
length += buffer.length + 1;
}
const encoded = Buffer.alloc(length);
encoded.writeUInt8(buffers.length);
let offset = 1;
for (const buffer of buffers) {
encoded.writeUInt8(buffer.length, offset);
offset += 1;
buffer.copy(encoded, offset);
offset += buffer.length;
}
return encoded;
}