Skip to content

Commit

Permalink
feat: add serialization helpers for transaction (#1706)
Browse files Browse the repository at this point in the history
Co-authored-by: janniks <[email protected]>
  • Loading branch information
janniks and janniks authored Jun 17, 2024
1 parent b9f8775 commit 2c57ea4
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
33 changes: 33 additions & 0 deletions packages/transactions/src/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,3 +293,36 @@ export function deserializeTransaction(tx: string | Uint8Array | BytesReader) {
chainId
);
}

/**
* Alias for `transaction.serialize()`
*
* Serializes a transaction to bytes.
*
* @example
* ```ts
* import { makeSTXTokenTransfer, serializeTransaction } from '@stacks/transactions';
*
* const transaction = makeSTXTokenTransfer({ ... });
* const bytes = serializeTransaction(transaction);
* ```
*/
export function serializeTransaction(transaction: StacksTransaction): Uint8Array {
// todo: refactor to hex instead of bytes for `next` release
return transaction.serialize();
}

/**
* Serializes a transaction to a hex string.
*
* @example
* ```ts
* import { makeSTXTokenTransfer, transactionToHex } from '@stacks/transactions';
*
* const transaction = makeSTXTokenTransfer({ ... });
* const hex = transactionToHex(transaction);
* ```
*/
export function transactionToHex(transaction: StacksTransaction): string {
return bytesToHex(transaction.serialize());
}
21 changes: 20 additions & 1 deletion packages/transactions/tests/transaction.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { deserializeTransaction, StacksTransaction } from '../src/transaction';
import {
deserializeTransaction,
serializeTransaction,
StacksTransaction,
transactionToHex,
} from '../src/transaction';

import {
createMultiSigSpendingCondition,
Expand Down Expand Up @@ -435,3 +440,17 @@ test('Coinbase pay to alt contract principal recipient deserialization', () => {
);
expect(deserializedTx.version).toBe(TransactionVersion.Testnet);
});

describe(serializeTransaction.name, () => {
const serializedTx =
'0x8080000000040055a0a92720d20398211cd4c7663d65d018efcc1f00000000000000030000000000000000010118da31f542913e8c56961b87ee4794924e655a28a2034e37ef4823eeddf074747285bd6efdfbd84eecdf62cffa7c1864e683c688f4c105f4db7429066735b4e2010200000000050000000000000000000000000000000000000000000000000000000000000000061aba27f99e007c7f605a8305e318c1abde3cd220ac0b68656c6c6f5f776f726c64';
const tx = deserializeTransaction(serializedTx);

test('alias of .serialize', () => {
expect(tx.serialize()).toEqual(serializeTransaction(tx));
});

test(transactionToHex.name, () => {
expect(transactionToHex(tx)).toEqual(bytesToHex(serializeTransaction(tx)));
});
});

0 comments on commit 2c57ea4

Please sign in to comment.