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 utility function to sign txs #270

Merged
merged 7 commits into from
Jun 19, 2024
Merged
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
37 changes: 37 additions & 0 deletions sui/sign-utils.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict';

const { verifyTransactionBlock } = require('@mysten/sui.js/verify');
const { decodeSuiPrivateKey } = require('@mysten/sui.js/cryptography');
const { Ed25519Keypair } = require('@mysten/sui.js/keypairs/ed25519');
const { Secp256k1Keypair } = require('@mysten/sui.js/keypairs/secp256k1');
Expand Down Expand Up @@ -100,10 +101,46 @@ async function broadcast(client, keypair, tx) {
});
}

async function signTransactionBlock(chain, txDetails, options) {
const { txBlock, buildOptions = {} } = txDetails;

const [keypair, client] = getWallet(chain, options);
txBlock.setSenderIfNotSet(keypair.toSuiAddress());
const txBytes = await txBlock.build(buildOptions);
const serializedSignature = (await keypair.signTransactionBlock(txBytes)).signature;
let publicKey;

try {
publicKey = await verifyTransactionBlock(txBytes, serializedSignature);
} catch {
throw new Error(`Cannot verify tx signature`);
}

if (publicKey.toSuiAddress() !== keypair.toSuiAddress()) {
throw new Error(`Verification failed for address ${keypair.toSuiAddress()}`);
}

if (!options.offline) {
const txResult = await client.executeTransactionBlock({
transactionBlock: txBytes,
signature: serializedSignature,
});

printInfo('Transaction result', JSON.stringify(txResult));
}

return {
signature: serializedSignature,
txBlock,
publicKey,
};
}

module.exports = {
getWallet,
printWalletInfo,
generateKeypair,
getRawPrivateKey,
broadcast,
signTransactionBlock,
};
Loading