Merge pull request #54 from switchboard-xyz/job-init-batching

job init changes
This commit is contained in:
gallynaut 2022-09-01 18:42:53 -06:00 committed by GitHub
commit 21fba9b97d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 70 additions and 32 deletions

View File

@ -1652,45 +1652,83 @@ export class JobAccount {
program: SwitchboardProgram,
params: JobInitParams
): Promise<JobAccount> {
const CHUNK_SIZE = 800;
const payerKeypair = programWallet(program);
const jobAccount = params.keypair ?? anchor.web3.Keypair.generate();
const size =
280 + params.data.length + (params.variables?.join("")?.length ?? 0);
const [stateAccount, stateBump] = await ProgramStateAccount.getOrCreate(
program,
{}
);
const state = await stateAccount.loadData();
await program.methods
.jobInit({
name: params.name ?? Buffer.from(""),
expiration: params.expiration ?? new anchor.BN(0),
data: params.data,
variables:
params.variables?.map((item) => Buffer.from("")) ??
new Array<Buffer>(),
stateBump,
})
.accounts({
job: jobAccount.publicKey,
authorWallet: params.authority,
authority: params.authority,
programState: stateAccount.publicKey,
})
.signers([jobAccount])
.preInstructions([
anchor.web3.SystemProgram.createAccount({
fromPubkey: programWallet(program).publicKey,
newAccountPubkey: jobAccount.publicKey,
space: size,
lamports:
await program.provider.connection.getMinimumBalanceForRentExemption(
size
),
programId: program.programId,
}),
])
.rpc();
if (params.data.byteLength <= CHUNK_SIZE) {
await program.methods
.jobInit({
name: params.name ?? Buffer.from(""),
expiration: params.expiration ?? new anchor.BN(0),
stateBump,
data: params.data,
size: null,
})
.accounts({
job: jobAccount.publicKey,
authority: params.authority,
programState: stateAccount.publicKey,
payer: payerKeypair.publicKey,
systemProgram: SystemProgram.programId,
})
.signers([jobAccount])
.rpc();
} else {
const chunks: Buffer[] = [];
for (let i = 0; i < params.data.byteLength; ) {
const end =
i + CHUNK_SIZE >= params.data.byteLength
? params.data.byteLength
: i + CHUNK_SIZE;
chunks.push(params.data.slice(i, end));
i = end;
}
const txns: string[] = [];
txns.push(
await program.methods
.jobInit({
name: [],
expiration: new anchor.BN(0),
stateBump,
data: Buffer.from(""),
size: params.data.byteLength,
})
.accounts({
job: jobAccount.publicKey,
authority: payerKeypair.publicKey,
programState: stateAccount.publicKey,
payer: payerKeypair.publicKey,
systemProgram: SystemProgram.programId,
})
.signers([jobAccount])
.rpc()
);
for await (const [n, chunk] of chunks.entries()) {
txns.push(
await program.methods
.jobSetData({
data: chunk,
size: params.data.byteLength,
chunkIdx: n,
})
.accounts({
job: jobAccount.publicKey,
authority: payerKeypair.publicKey,
})
.rpc()
);
}
}
return new JobAccount({ program, keypair: jobAccount });
}