Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 64 additions & 10 deletions clients/js/src/generated/instructions/write.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,15 @@ import {
combineCodec,
getBytesDecoder,
getBytesEncoder,
getOptionDecoder,
getOptionEncoder,
getStructDecoder,
getStructEncoder,
getU32Decoder,
getU32Encoder,
getU8Decoder,
getU8Encoder,
none,
transformEncoder,
type Address,
type Codec,
Expand All @@ -26,6 +29,9 @@ import {
type IInstruction,
type IInstructionWithAccounts,
type IInstructionWithData,
type Option,
type OptionOrNullable,
type ReadonlyAccount,
type ReadonlySignerAccount,
type ReadonlyUint8Array,
type TransactionSigner,
Expand All @@ -44,6 +50,7 @@ export type WriteInstruction<
TProgram extends string = typeof PROGRAM_METADATA_PROGRAM_ADDRESS,
TAccountBuffer extends string | IAccountMeta<string> = string,
TAccountAuthority extends string | IAccountMeta<string> = string,
TAccountSourceBuffer extends string | IAccountMeta<string> = string,
TRemainingAccounts extends readonly IAccountMeta<string>[] = [],
> = IInstruction<TProgram> &
IInstructionWithData<Uint8Array> &
Expand All @@ -56,6 +63,9 @@ export type WriteInstruction<
? ReadonlySignerAccount<TAccountAuthority> &
IAccountSignerMeta<TAccountAuthority>
: TAccountAuthority,
TAccountSourceBuffer extends string
? ReadonlyAccount<TAccountSourceBuffer>
: TAccountSourceBuffer,
...TRemainingAccounts,
]
>;
Expand All @@ -64,31 +74,43 @@ export type WriteInstructionData = {
discriminator: number;
/** The offset to write to. */
offset: number;
data: ReadonlyUint8Array;
/**
* The data to write at the provided offset.
* You may use the `source_buffer` account instead of this argument to copy from an existing buffer.
*/
data: Option<ReadonlyUint8Array>;
};

export type WriteInstructionDataArgs = {
/** The offset to write to. */
offset: number;
data: ReadonlyUint8Array;
/**
* The data to write at the provided offset.
* You may use the `source_buffer` account instead of this argument to copy from an existing buffer.
*/
data?: OptionOrNullable<ReadonlyUint8Array>;
};

export function getWriteInstructionDataEncoder(): Encoder<WriteInstructionDataArgs> {
return transformEncoder(
getStructEncoder([
['discriminator', getU8Encoder()],
['offset', getU32Encoder()],
['data', getBytesEncoder()],
['data', getOptionEncoder(getBytesEncoder(), { prefix: null })],
]),
(value) => ({ ...value, discriminator: WRITE_DISCRIMINATOR })
(value) => ({
...value,
discriminator: WRITE_DISCRIMINATOR,
data: value.data ?? none(),
})
);
}

export function getWriteInstructionDataDecoder(): Decoder<WriteInstructionData> {
return getStructDecoder([
['discriminator', getU8Decoder()],
['offset', getU32Decoder()],
['data', getBytesDecoder()],
['data', getOptionDecoder(getBytesDecoder(), { prefix: null })],
]);
}

Expand All @@ -105,23 +127,35 @@ export function getWriteInstructionDataCodec(): Codec<
export type WriteInput<
TAccountBuffer extends string = string,
TAccountAuthority extends string = string,
TAccountSourceBuffer extends string = string,
> = {
/** The buffer to write to. */
buffer: Address<TAccountBuffer>;
/** The authority of the buffer. */
authority: TransactionSigner<TAccountAuthority>;
/**
* Buffer to copy the data from.
* You may use the `data` argument instead of this account to pass data directly.
*/
sourceBuffer?: Address<TAccountSourceBuffer>;
offset: WriteInstructionDataArgs['offset'];
data: WriteInstructionDataArgs['data'];
data?: WriteInstructionDataArgs['data'];
};

export function getWriteInstruction<
TAccountBuffer extends string,
TAccountAuthority extends string,
TAccountSourceBuffer extends string,
TProgramAddress extends Address = typeof PROGRAM_METADATA_PROGRAM_ADDRESS,
>(
input: WriteInput<TAccountBuffer, TAccountAuthority>,
input: WriteInput<TAccountBuffer, TAccountAuthority, TAccountSourceBuffer>,
config?: { programAddress?: TProgramAddress }
): WriteInstruction<TProgramAddress, TAccountBuffer, TAccountAuthority> {
): WriteInstruction<
TProgramAddress,
TAccountBuffer,
TAccountAuthority,
TAccountSourceBuffer
> {
// Program address.
const programAddress =
config?.programAddress ?? PROGRAM_METADATA_PROGRAM_ADDRESS;
Expand All @@ -130,6 +164,7 @@ export function getWriteInstruction<
const originalAccounts = {
buffer: { value: input.buffer ?? null, isWritable: true },
authority: { value: input.authority ?? null, isWritable: false },
sourceBuffer: { value: input.sourceBuffer ?? null, isWritable: false },
};
const accounts = originalAccounts as Record<
keyof typeof originalAccounts,
Expand All @@ -144,12 +179,18 @@ export function getWriteInstruction<
accounts: [
getAccountMeta(accounts.buffer),
getAccountMeta(accounts.authority),
getAccountMeta(accounts.sourceBuffer),
],
programAddress,
data: getWriteInstructionDataEncoder().encode(
args as WriteInstructionDataArgs
),
} as WriteInstruction<TProgramAddress, TAccountBuffer, TAccountAuthority>;
} as WriteInstruction<
TProgramAddress,
TAccountBuffer,
TAccountAuthority,
TAccountSourceBuffer
>;

return instruction;
}
Expand All @@ -164,6 +205,12 @@ export type ParsedWriteInstruction<
buffer: TAccountMetas[0];
/** The authority of the buffer. */
authority: TAccountMetas[1];
/**
* Buffer to copy the data from.
* You may use the `data` argument instead of this account to pass data directly.
*/

sourceBuffer?: TAccountMetas[2] | undefined;
};
data: WriteInstructionData;
};
Expand All @@ -176,7 +223,7 @@ export function parseWriteInstruction<
IInstructionWithAccounts<TAccountMetas> &
IInstructionWithData<Uint8Array>
): ParsedWriteInstruction<TProgram, TAccountMetas> {
if (instruction.accounts.length < 2) {
if (instruction.accounts.length < 3) {
// TODO: Coded error.
throw new Error('Not enough accounts');
}
Expand All @@ -186,11 +233,18 @@ export function parseWriteInstruction<
accountIndex += 1;
return accountMeta;
};
const getNextOptionalAccount = () => {
const accountMeta = getNextAccount();
return accountMeta.address === PROGRAM_METADATA_PROGRAM_ADDRESS
? undefined
: accountMeta;
};
return {
programAddress: instruction.programAddress,
accounts: {
buffer: getNextAccount(),
authority: getNextAccount(),
sourceBuffer: getNextOptionalAccount(),
},
data: getWriteInstructionDataDecoder().decode(instruction.data),
};
Expand Down
46 changes: 46 additions & 0 deletions clients/js/test/write.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,49 @@ test('it appends to the end of buffers when doing multiple writes', async (t) =>
data: new Uint8Array([...dataChunk1, ...dataChunk2]),
});
});

test('it writes to buffers using other buffers', async (t) => {
// Given the following authority and deployed program.
const client = createDefaultSolanaClient();
const authority = await generateKeyPairSignerWithSol(client);
const [program, programData] = await createDeployedProgram(client, authority);

// And an existing keypair buffer account with data.
const data = getUtf8Encoder().encode('Hello, World!');
const sourceBuffer = await createKeypairBuffer(client, {
payer: authority,
data,
});

// And the following pre-allocated pre-funded empty canonical buffer account.
const seed = 'dummy';
const [buffer] = await createCanonicalBuffer(client, {
authority,
program,
programData,
seed,
dataLength: data.length,
});

// When we write some data to the canonical buffer account
// using the keypair buffer account as source.
const writeIx = getWriteInstruction({
buffer,
authority,
offset: 0,
sourceBuffer: sourceBuffer.address,
});
await pipe(
await createDefaultTransaction(client, authority),
(tx) => appendTransactionMessageInstruction(writeIx, tx),
(tx) => signAndSendTransaction(client, tx)
);

// Then we expect the buffer account to contain the data from the source buffer.
const bufferAccount = await fetchBuffer(client.rpc, buffer);
t.like(bufferAccount.data, <Partial<Buffer>>{
discriminator: AccountDiscriminator.Buffer,
canonical: true,
data,
});
});
Loading