Skip to content

Commit

Permalink
feat(sdk): make ordinals content as chunks before building witness
Browse files Browse the repository at this point in the history
  • Loading branch information
kranthicodes committed Jun 26, 2023
1 parent d240e13 commit f7c5d34
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 13 deletions.
2 changes: 1 addition & 1 deletion packages/sdk/src/inscription/psbt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ export async function createRevealPsbt(options: CreateRevealPsbtOptions) {
value: options.postage
});

if (change) {
if (change > 600) {
let changeAddress = inscribePayTx.address;
if (options.changeAddress) {
changeAddress = options.changeAddress;
Expand Down
47 changes: 35 additions & 12 deletions packages/sdk/src/inscription/witness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ export function buildWitnessScript(options: WitnessScriptOptions) {
throw new Error("Failed to build witness script");
}

const contentChunks = chunkContent(options.mediaContent);

const metaStackElements =
typeof options.meta === "object"
? [
Expand All @@ -22,18 +24,34 @@ export function buildWitnessScript(options: WitnessScriptOptions) {
]
: [];

const baseStackElements = [
Buffer.from(options.xkey, "hex"),
bitcoin.opcodes.OP_CHECKSIG,
bitcoin.opcodes.OP_FALSE,
bitcoin.opcodes.OP_IF,
opPush("ord"),
1,
1,
opPush(options.mediaType),
bitcoin.opcodes.OP_0
];

const contentStackElements: (number | Buffer)[] = [];

if (contentChunks) {
contentChunks.forEach((chunk) => {
let encoding: BufferEncoding = "utf8";
if (options.mediaType.indexOf("text") < 0) {
encoding = "base64";
}
contentStackElements.push(opPush(chunk, encoding));
});
}

try {
const witness = bitcoin.script.compile([
Buffer.from(options.xkey, "hex"),
bitcoin.opcodes.OP_CHECKSIG,
bitcoin.opcodes.OP_FALSE,
bitcoin.opcodes.OP_IF,
opPush("ord"),
1,
1,
opPush(options.mediaType),
bitcoin.opcodes.OP_0,
opPush(options.mediaContent),
...baseStackElements,
...contentStackElements,
bitcoin.opcodes.OP_ENDIF,
...metaStackElements
]);
Expand All @@ -46,13 +64,18 @@ export function buildWitnessScript(options: WitnessScriptOptions) {
return false;
}

function opPush(str: string) {
const buff = Buffer.from(str, "utf8");
function opPush(str: string, encoding: BufferEncoding = "utf8") {
const buff = Buffer.from(str, encoding);
const obj = [buff];
const push = Buffer.concat(obj);
return push;
}

const chunkContent = function (str: string) {
const chunkList = str.match(/.{1,520}/g);
return chunkList;
};

export type WitnessScriptOptions = {
xkey: string;
mediaContent: string;
Expand Down

0 comments on commit f7c5d34

Please sign in to comment.