Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding batch IX processing. #199

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
92 changes: 92 additions & 0 deletions clients/js/baseline.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
[
{
"name": "CU: create a new, empty asset",
"unit": "Compute Units",
"value": 9863
},
{
"name": "Space: create a new, empty asset",
"unit": "Bytes",
"value": 91
},
{
"name": "CU: create a new, empty asset with empty collection",
"unit": "Compute Units",
"value": 21491
},
{
"name": "Space: create a new, empty asset with empty collection",
"unit": "Bytes",
"value": 91
},
{
"name": "CU: create a new asset with plugins",
"unit": "Compute Units",
"value": 39333
},
{
"name": "Space: create a new asset with plugins",
"unit": "Bytes",
"value": 194
},
{
"name": "CU: create a new asset with plugins and empty collection",
"unit": "Compute Units",
"value": 45133
},
{
"name": "Space: create a new asset with plugins and empty collection",
"unit": "Bytes",
"value": 194
},
{
"name": "CU: list an asset",
"unit": "Compute Units",
"value": 30912
},
{
"name": "CU: sell an asset",
"unit": "Compute Units",
"value": 37720
},
{
"name": "CU: list an asset with empty collection",
"unit": "Compute Units",
"value": 39073
},
{
"name": "CU: sell an asset with empty collection",
"unit": "Compute Units",
"value": 50953
},
{
"name": "CU: list an asset with collection royalties",
"unit": "Compute Units",
"value": 40358
},
{
"name": "CU: sell an asset with collection royalties",
"unit": "Compute Units",
"value": 56517
},
{
"name": "CU: transfer an empty asset",
"unit": "Compute Units",
"value": 5292
},
{
"name": "CU: transfer an empty asset with empty collection",
"unit": "Compute Units",
"value": 8066
},
{
"name": "CU: transfer an asset with plugins",
"unit": "Compute Units",
"value": 11493
},
{
"name": "CU: transfer an asset with plugins and empty collection",
"unit": "Compute Units",
"value": 14267
}
]
88 changes: 87 additions & 1 deletion clients/js/bench/transfer.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { generateSigner, TransactionBuilder } from "@metaplex-foundation/umi";
import test from "ava";
import { existsSync, readFileSync, writeFileSync } from "fs";
import { createCollectionV1, createV1, pluginAuthorityPair, ruleSet, transferV1 } from "../src";
import { batch, createCollectionV1, createV1, pluginAuthorityPair, ruleSet, transferV1 } from "../src";
import { createUmi } from "./_setup";

test('transfer an empty asset', async (t) => {
Expand Down Expand Up @@ -204,5 +204,91 @@ test('transfer an asset with plugins and empty collection', async (t) => {
// Write the array to output.json
writeFileSync("./output.json", JSON.stringify(output, null, 2));

t.pass();
});

test('transfer an empty asset 36 times separate instructions', async (t) => {
// Given an Umi instance and a new signer.
const umi = await createUmi();
const assetAddress = generateSigner(umi);
const newOwner = generateSigner(umi);

await createV1(umi, {
asset: assetAddress,
name: "Test",
uri: "www.test.com",
}).sendAndConfirm(umi);

let builder = new TransactionBuilder();

for (let i = 0; i < 18; i += 1) {
builder = builder.add(transferV1(umi, { asset: assetAddress.publicKey, newOwner: newOwner.publicKey }));
builder = builder.add(transferV1(umi, { asset: assetAddress.publicKey, newOwner: umi.identity.publicKey, authority: newOwner }));
}

const tx = await builder.sendAndConfirm(umi);

const compute = Number((await umi.rpc.getTransaction(tx.signature))?.meta.computeUnitsConsumed);

const cuResult = {
name: `CU: ${t.title}`,
unit: "Compute Units",
value: compute,
}

// Read the results array from output.json
let output = [];
if (existsSync("./output.json")) {
output = JSON.parse(readFileSync("./output.json", 'utf-8'));
}

// Push the result to the array
output.push(cuResult);
// Write the array to output.json
writeFileSync("./output.json", JSON.stringify(output, null, 2));

t.pass();
});

test('transfer an empty asset 36 times in a batch instruction', async (t) => {
// Given an Umi instance and a new signer.
const umi = await createUmi();
const assetAddress = generateSigner(umi);
const newOwner = generateSigner(umi);

await createV1(umi, {
asset: assetAddress,
name: "Test",
uri: "www.test.com",
}).sendAndConfirm(umi);

let builder = new TransactionBuilder();

for (let i = 0; i < 18; i += 1) {
builder = builder.add(transferV1(umi, { asset: assetAddress.publicKey, newOwner: newOwner.publicKey }));
builder = builder.add(transferV1(umi, { asset: assetAddress.publicKey, newOwner: umi.identity.publicKey, authority: newOwner }));
}

const tx = await batch(umi, builder).sendAndConfirm(umi);

const compute = Number((await umi.rpc.getTransaction(tx.signature))?.meta.computeUnitsConsumed);

const cuResult = {
name: `CU: ${t.title}`,
unit: "Compute Units",
value: compute,
}

// Read the results array from output.json
let output = [];
if (existsSync("./output.json")) {
output = JSON.parse(readFileSync("./output.json", 'utf-8'));
}

// Push the result to the array
output.push(cuResult);
// Write the array to output.json
writeFileSync("./output.json", JSON.stringify(output, null, 2));

t.pass();
});
114 changes: 114 additions & 0 deletions clients/js/src/generated/instructions/batchV1.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/**
* This code was AUTOGENERATED using the kinobi library.
* Please DO NOT EDIT THIS FILE, instead use visitors
* to add features, then rerun kinobi to update it.
*
* @see https://github.com/metaplex-foundation/kinobi
*/

import {
Context,
Pda,
PublicKey,
TransactionBuilder,
transactionBuilder,
} from '@metaplex-foundation/umi';
import {
Serializer,
bytes,
mapSerializer,
struct,
u32,
u8,
} from '@metaplex-foundation/umi/serializers';
import {
ResolvedAccount,
ResolvedAccountsWithIndices,
getAccountMetasAndSigners,
} from '../shared';

// Accounts.
export type BatchV1InstructionAccounts = {
/** Dummy account */
dummy?: PublicKey | Pda;
};

// Data.
export type BatchV1InstructionData = {
discriminator: number;
numAccounts: Uint8Array;
instructions: Uint8Array;
};

export type BatchV1InstructionDataArgs = {
numAccounts: Uint8Array;
instructions: Uint8Array;
};

export function getBatchV1InstructionDataSerializer(): Serializer<
BatchV1InstructionDataArgs,
BatchV1InstructionData
> {
return mapSerializer<BatchV1InstructionDataArgs, any, BatchV1InstructionData>(
struct<BatchV1InstructionData>(
[
['discriminator', u8()],
['numAccounts', bytes({ size: u32() })],
['instructions', bytes({ size: u32() })],
],
{ description: 'BatchV1InstructionData' }
),
(value) => ({ ...value, discriminator: 31 })
) as Serializer<BatchV1InstructionDataArgs, BatchV1InstructionData>;
}

// Args.
export type BatchV1InstructionArgs = BatchV1InstructionDataArgs;

// Instruction.
export function batchV1(
context: Pick<Context, 'programs'>,
input: BatchV1InstructionAccounts & BatchV1InstructionArgs
): TransactionBuilder {
// Program ID.
const programId = context.programs.getPublicKey(
'mplCore',
'CoREENxT6tW1HoK8ypY1SxRMZTcVPm7R94rH4PZNhX7d'
);

// Accounts.
const resolvedAccounts = {
dummy: {
index: 0,
isWritable: false as boolean,
value: input.dummy ?? null,
},
} satisfies ResolvedAccountsWithIndices;

// Arguments.
const resolvedArgs: BatchV1InstructionArgs = { ...input };

// Accounts in order.
const orderedAccounts: ResolvedAccount[] = Object.values(
resolvedAccounts
).sort((a, b) => a.index - b.index);

// Keys and Signers.
const [keys, signers] = getAccountMetasAndSigners(
orderedAccounts,
'programId',
programId
);

// Data.
const data = getBatchV1InstructionDataSerializer().serialize(
resolvedArgs as BatchV1InstructionDataArgs
);

// Bytes Created On Chain.
const bytesCreatedOnChain = 0;

return transactionBuilder([
{ instruction: { keys, programId, data }, signers, bytesCreatedOnChain },
]);
}
1 change: 1 addition & 0 deletions clients/js/src/generated/instructions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export * from './addExternalPluginAdapterV1';
export * from './addPluginV1';
export * from './approveCollectionPluginAuthorityV1';
export * from './approvePluginAuthorityV1';
export * from './batchV1';
export * from './burnCollectionV1';
export * from './burnV1';
export * from './collect';
Expand Down
38 changes: 38 additions & 0 deletions clients/js/src/instructions/batch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import {
AccountMeta,
Context,
Signer,
TransactionBuilder,
} from '@metaplex-foundation/umi';
import { batchV1 } from '../generated';

export const batch = (
context: Pick<Context, 'payer' | 'programs' | 'eddsa' | 'identity'>,
builder: TransactionBuilder
) => {
const ixes = builder.items;
let numAccounts = Buffer.alloc(0);
let instructions = Buffer.alloc(0);
const remainingAccounts: AccountMeta[] = [];
const signers: Signer[] = [];

ixes.forEach((ix) => {
numAccounts = Buffer.concat([
numAccounts,
Buffer.from([ix.instruction.keys.length]),
]);
instructions = Buffer.concat([instructions, ix.instruction.data]);
remainingAccounts.push(...ix.instruction.keys);
signers.push(...ix.signers);
});

const batchBuilder = batchV1(context, {
numAccounts,
instructions,
}).addRemainingAccounts(remainingAccounts);

const batchBuilderItems = batchBuilder.items;
batchBuilderItems[0].signers.push(...signers);
batchBuilder.setItems(batchBuilderItems);
return batchBuilder;
};
1 change: 1 addition & 0 deletions clients/js/src/instructions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ export * from './approvePluginAuthority';
export * from './revokePluginAuthority';
export * from './collection';
export * from './writeData';
export * from './batch';
Loading
Loading