@spacemesh/sm-codec
TypeScript library provides easy way to encode, decode, and sign transactions.
See usage examples below:
import { SingleSigTemplate, StdMethods } from '@spacemesh/sm-codec';
import { sign } from '@noble/ed25519';
(() => {
const spawnTpl = SingleSigTemplate.methods[StdMethods.Spawn];
const spawnPayload = {
Nonce: 0n,
GasPrice: 1n,
Arguments: {
PublicKey: Uint8Array.from([]),
},
};
const principal = spawnTpl.principal(spawnPayload.Arguments);
const rawTx = spawnTpl.encode(principal, spawnPayload);
const txHash = hash(rawTx);
const sig = sign(myPrivateKey, txHash);
const signedTx = spawnTpl.sign(rawTx, sig);
SingleSigTemplate.methods[StdMethods.Spend].principal(spawnPayload.Arguments);
})();
Example of creating your own template:
import { PublicKey, SingleSig, Codecs } from '@spacemesh/sm-codec';
import { Struct, str } from 'scale-ts';
const spawnCodec = Struct({
Owner: PublicKey,
});
const saySmthCodec = Struct({
message: str,
})
const address = Uint8Array.from([
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 100,
]);
const spawnTpl = new Transaction({
address,
methodSelector: 0,
spawnArgsCodec: spawnCodec,
payloadCodec: withTemplateAddress(address, spawnCodec),
sigCodec: SingleSig,
});
const saySmthTpl =
new Transaction({
address,
methodSelector: 1,
spawnArgsCodec: spawnCodec,
payloadCodec: saySmthCodec,
sigCodec: SingleSig,
});
const principal = saySmthTpl.principal({
Owner: Uint8Array.from([ ]),
});
const rawTx = saySmthTpl.encode(principal, {
message: 'hello world',
});
})();