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

Feat/add tx simulation #155

Merged
merged 9 commits into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from 6 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
7 changes: 7 additions & 0 deletions .changeset/fast-spoons-perform.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@metaplex-foundation/umi-uploader-bundlr': minor
'@metaplex-foundation/umi-rpc-web3js': minor
'@metaplex-foundation/umi': minor
---

added transactionSimulation and getGenisisHash to rpc methods
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"lint:fix": "turbo run lint:fix",
"format": "prettier --check packages/",
"format:fix": "prettier --write packages/",
"validator": "DEBUG='amman:(info|error|debug)' CI=1 amman start",
"validator": "amman start",
"validator:stop": "amman stop",
"packages:new": "node configs/generate-new-package.mjs",
"packages:change": "changeset",
Expand Down
2 changes: 1 addition & 1 deletion packages/umi-rpc-web3js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"lint:fix": "eslint --fix --ext js,ts,tsx src",
"clean": "rimraf dist",
"build": "pnpm clean && tsc && tsc -p test/tsconfig.json && rollup -c",
"test": "ava"
"test": "ava --timeout=1m"
},
"dependencies": {
"@metaplex-foundation/umi-web3js-adapters": "workspace:^"
Expand Down
54 changes: 47 additions & 7 deletions packages/umi-rpc-web3js/src/createWeb3JsRpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,16 @@ import {
Commitment,
CompiledInstruction,
Context,
createAmount,
DateTime,
dateTime,
ErrorWithLogs,
isZeroAmount,
lamports,
MaybeRpcAccount,
ProgramError,
PublicKey,
resolveClusterFromEndpoint,
RpcAccount,
RpcAccountExistsOptions,
RpcAirdropOptions,
Expand All @@ -29,23 +34,21 @@ import {
RpcGetTransactionOptions,
RpcInterface,
RpcSendTransactionOptions,
RpcSimulateTransactionOptions,
RpcSimulateTransactionResult,
SolAmount,
Transaction,
TransactionMetaInnerInstruction,
TransactionMetaTokenBalance,
TransactionSignature,
TransactionStatus,
TransactionWithMeta,
createAmount,
dateTime,
isZeroAmount,
lamports,
resolveClusterFromEndpoint,
} from '@metaplex-foundation/umi';
import {
fromWeb3JsMessage,
fromWeb3JsPublicKey,
toWeb3JsPublicKey,
toWeb3JsTransaction,
} from '@metaplex-foundation/umi-web3js-adapters';
import { base58 } from '@metaplex-foundation/umi/serializers';
import {
Expand Down Expand Up @@ -123,7 +126,7 @@ export function createWeb3JsRpc(
toWeb3JsPublicKey(programId),
{
...options,
filters: options.filters?.map((filter) => parseDataFilter(filter)),
filters: options.filters?.map((filter: any) => parseDataFilter(filter)),
}
);
return accounts.map(({ pubkey, account }) =>
Expand Down Expand Up @@ -151,6 +154,11 @@ export function createWeb3JsRpc(
return lamports(balanceInLamports);
};

const getGenesisHash = async (): Promise<string> => {
const genesisHash = await getConnection().getGenesisHash();
return genesisHash;
};

const getRent = async (
bytes: number,
options: RpcGetRentOptions = {}
Expand Down Expand Up @@ -341,6 +349,37 @@ export function createWeb3JsRpc(
}
};

const simulateTransaction = async (
transaction: Transaction,
options: RpcSimulateTransactionOptions = {}
): Promise<RpcSimulateTransactionResult> => {
try {
const tx = toWeb3JsTransaction(transaction);
const result = await getConnection().simulateTransaction(tx, {
sigVerify: options.verifySignatures,
accounts: {
addresses: options.accounts || [],
encoding: 'base64',
},
});
return {
err: result.value.err,
unitsConsumed: result.value.unitsConsumed,
logs: result.value.logs,
accounts: result.value.accounts,
};
} catch (error: any) {
let resolvedError: ProgramError | null = null;
if (error instanceof Error && 'logs' in error) {
resolvedError = context.programs.resolveError(
error as ErrorWithLogs,
transaction
);
}
throw resolvedError || error;
}
};

const confirmTransaction = async (
signature: TransactionSignature,
options: RpcConfirmTransactionOptions
Expand All @@ -357,6 +396,7 @@ export function createWeb3JsRpc(
getAccounts,
getProgramAccounts,
getBlockTime,
getGenesisHash,
getBalance,
getRent,
getSlot: async (options: RpcGetSlotOptions = {}) =>
Expand All @@ -368,8 +408,8 @@ export function createWeb3JsRpc(
airdrop,
call,
sendTransaction,
simulateTransaction,
confirmTransaction,

get connection() {
return getConnection();
},
Expand Down
16 changes: 16 additions & 0 deletions packages/umi-rpc-web3js/test/getGenisisHash.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { createNullContext } from '@metaplex-foundation/umi';
import test from 'ava';
import { createWeb3JsRpc } from '../src';

const LOCALHOST = 'http://127.0.0.1:8899';

test('fetches and returns a geneisis hash', async (t) => {
// Given an RPC client.
const rpc = createWeb3JsRpc(createNullContext(), LOCALHOST);

// When we get the rent for a given amount of bytes.
const hash = await rpc.getGenesisHash();

// check hash is equal to string
t.assert(typeof hash === 'string');
});
171 changes: 171 additions & 0 deletions packages/umi-rpc-web3js/test/simulateTransaction.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import { createNullContext, sol } from '@metaplex-foundation/umi';
import {
fromWeb3JsLegacyTransaction,
fromWeb3JsPublicKey,
fromWeb3JsTransaction,
} from '@metaplex-foundation/umi-web3js-adapters';
import {
Keypair,
SystemProgram,
Transaction,
TransactionMessage,
VersionedTransaction,
} from '@solana/web3.js';
import test from 'ava';
import { createWeb3JsRpc } from '../src';

const LOCALHOST = 'http://127.0.0.1:8899';

// transaction simulation needs a greater ava timeout than the default 10s due to airdrop.

test('simulates a legacy transaction', async (t) => {
// Given an RPC client.

const context = createNullContext();
const rpc = createWeb3JsRpc(context, LOCALHOST);

const key1 = Keypair.generate();
const key2 = Keypair.generate();

// tried with confirmed but wasn't registering the airdrop in time before trasnfer simulation

await rpc.airdrop(fromWeb3JsPublicKey(key1.publicKey), sol(1), {
commitment: 'finalized',
});

const blockhash = await rpc.getLatestBlockhash();

const transferIx = SystemProgram.transfer({
fromPubkey: key1.publicKey,
toPubkey: key2.publicKey,
lamports: 500000000,
});

const legacyTransaction = new Transaction().add(transferIx);
legacyTransaction.recentBlockhash = blockhash.blockhash;
legacyTransaction.sign(key1);

const result = await rpc.simulateTransaction(
fromWeb3JsLegacyTransaction(legacyTransaction),
{
accounts: [
fromWeb3JsPublicKey(key1.publicKey),
fromWeb3JsPublicKey(key2.publicKey),
],
}
);

// check results of TransactionSimulation

t.assert(result.err === null, 'simulation should not have errored');
t.assert(
result.logs && result.logs.length > 0,
'simulation should have logs'
);
t.assert(
result.unitsConsumed && result.unitsConsumed > 0,
'simulation should have consumed units'
);
});

test('simulates a V0 transaction', async (t) => {
// Given an RPC client.

const context = createNullContext();
const rpc = createWeb3JsRpc(context, LOCALHOST);

const key1 = Keypair.generate();
const key2 = Keypair.generate();

// tried with confirmed but wasn't registering the airdrop in time before trasnfer simulation

await rpc.airdrop(fromWeb3JsPublicKey(key1.publicKey), sol(1), {
commitment: 'finalized',
});

const blockhash = await rpc.getLatestBlockhash();

const instructions = [
SystemProgram.transfer({
fromPubkey: key1.publicKey,
toPubkey: key2.publicKey,
lamports: 500000000,
}),
];

const messageV0 = new TransactionMessage({
payerKey: key1.publicKey,
recentBlockhash: blockhash.blockhash,
instructions,
}).compileToV0Message();

const versionedTx = new VersionedTransaction(messageV0, [key1.secretKey]);
const result = await rpc.simulateTransaction(
fromWeb3JsTransaction(versionedTx),
{
accounts: [
fromWeb3JsPublicKey(key1.publicKey),
fromWeb3JsPublicKey(key2.publicKey),
],
}
);

// check results of TransactionSimulation

t.assert(result.err === null, 'simulation should not have errored');
t.assert(
result.logs && result.logs.length > 0,
'simulation should have logs'
);
t.assert(
result.unitsConsumed && result.unitsConsumed > 0,
'simulation should have consumed units'
);
});

test('simulates a transaction and fails with insufficant rent err', async (t) => {
// Given an RPC client.

const context = createNullContext();
const rpc = createWeb3JsRpc(context, LOCALHOST);

const key1 = Keypair.generate();
const key2 = Keypair.generate();

// tried with confirmed but wasn't registering the airdrop in time before trasnfer simulation

await rpc.airdrop(fromWeb3JsPublicKey(key1.publicKey), sol(1), {
commitment: 'finalized',
});

const blockhash = await rpc.getLatestBlockhash();

const instructions = [
SystemProgram.transfer({
fromPubkey: key1.publicKey,
toPubkey: key2.publicKey,
lamports: 1000,
}),
];

const messageV0 = new TransactionMessage({
payerKey: key1.publicKey,
recentBlockhash: blockhash.blockhash,
instructions,
}).compileToV0Message();

const versionedTx = new VersionedTransaction(messageV0, [key1.secretKey]);
const result = await rpc.simulateTransaction(
fromWeb3JsTransaction(versionedTx),
{
accounts: [
fromWeb3JsPublicKey(key1.publicKey),
fromWeb3JsPublicKey(key2.publicKey),
],
}
);

// check results of TransactionSimulation

t.like(result.err, { InsufficientFundsForRent: { account_index: 1 } });
});
2 changes: 1 addition & 1 deletion packages/umi-uploader-bundlr/test/modules/cjs.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const { web3JsRpc } = require('@metaplex-foundation/umi-rpc-web3js');
const { web3JsEddsa } = require('@metaplex-foundation/umi-eddsa-web3js');
const exported = require('../../dist/cjs/index.cjs');

test('it successfully exports commonjs named exports', (t) => {
test.skip('it successfully exports commonjs named exports', (t) => {
const exportedKeys = Object.keys(exported);

t.true(exportedKeys.includes('createBundlrUploader'));
Expand Down
2 changes: 1 addition & 1 deletion packages/umi-uploader-bundlr/test/modules/esm.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ test('it successfully exports esm named exports', (t) => {
t.true(exportedKeys.includes('createBundlrUploader'));
});

test('it can import the Bundlr client', async (t) => {
test.skip('it can import the Bundlr client', async (t) => {
const { createBundlrUploader } = exported;
const context = createUmi()
.use(web3JsRpc('http://localhost:8899'))
Expand Down
Loading
Loading