Skip to content

Commit

Permalink
feat(sdk): integrate Inscriber w/ PSBTBuilder (#63)
Browse files Browse the repository at this point in the history
* refactor: initial integration w/ PSBTBuilder

* refactor: remove unncessary try..catch block

* refactor: update import path

* refactor: bind input payload to derived class member

* fix: use await for async fn

* fix: ignore precalculated postage

also, reduce usage of extra variables

* refactor!: make props required

* chore: ignore dist directory

* refactor: enable `inscriberMode` in OrdTransaction

* chore: exclude nod_modules & dist dir from vscode search

* feat: rename `OrdTransaction` to `Inscriber`

also, deprecate OrdTransaction class

* refactor: rename arg options type

* refactor: replace deprecated class name w/ new one

* refactor: rename file

* refactor!: remove defaults, rename & rearrange args

* refactor: remove unwanted getter

* feat!: remove support for change in Inscriber

Not possible to know what original utxo sats would be to calculate change

* feat: add preview mode flag and restrict specific operation

* refactor: move duplicate code to fn

* refactor: update collection publish & mint example

* refactor: update create-psbt example

* chore: deprecate irrelevant methods from Ordit class

* refactor: update property name

* refactor: update create collection and mint example

* refactor: update publish collection example
  • Loading branch information
iamcrazycoder authored Sep 20, 2023
1 parent 7c78e61 commit 4b0e73a
Show file tree
Hide file tree
Showing 10 changed files with 395 additions and 452 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,5 @@ logs
*.log
npm-debug.log*
lerna-debug.log*

**/dist
4 changes: 4 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,9 @@
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"search.exclude": {
"**/dist": true,
"**/node_modules": true
}
}
124 changes: 61 additions & 63 deletions examples/node/collections.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,46 @@
import { Ordit } from "@sadoprotocol/ordit-sdk";
import { Ordit, mintFromCollection, publishCollection } from "@sadoprotocol/ordit-sdk";

const WORDS = "<MNEMONIC PHRASE>";
const mnemonic = "<MNEMONIC PHRASE>";
const network = "testnet"

// User is the party who would mint the assets from a collection
const userWallet = new Ordit({
bip39: mnemonic,
network
});

// Publisher is the marketplace and any party owning the on-chain collection
const publisherWallet = new Ordit({
bip39: mnemonic,
network
});

// set default address types for both wallets
userWallet.setDefaultAddress("taproot");
publisherWallet.setDefaultAddress("nested-segwit");

async function publish() {
// Load wallet
const wallet = new Ordit({
bip39: WORDS,
network: "testnet"
});
const getPublisherLegacyAddress = () => {
publisherWallet.setDefaultAddress("legacy")
const legacyAddress = publisherWallet.selectedAddress
publisherWallet.setDefaultAddress("nested-segwit") // switch back to default

//set default taproot
wallet.setDefaultAddress("taproot");
return legacyAddress
}

//publish
const transaction = await Ordit.collection.publish({
const transaction = await publishCollection({
network,
feeRate: 2,
title: "Collection Name",
description: "Lorem ipsum something else",
slug: "collection-name",
creator: {
address: wallet.selectedAddress,
address: publisherWallet.selectedAddress,
email: "[email protected]",
name: "Your Name"
},
publishers: ["<publisher-legacy-address>"],
publishers: [getPublisherLegacyAddress()],
inscriptions: [
{
iid: "el-01",
Expand All @@ -36,93 +54,73 @@ async function publish() {
}
],
url: "https://example.com",
publicKey: wallet.publicKey,
destination: wallet.selectedAddress,
changeAddress: wallet.selectedAddress,
publicKey: publisherWallet.publicKey,
destination: publisherWallet.selectedAddress,
changeAddress: publisherWallet.selectedAddress,
postage: 1000,
mediaContent: 'Collection Name', // this will be inscribed on-chain as primary content
mediaType: "text/plain"
});

const depositDetails = transaction.generateCommit();
const depositDetails = await transaction.generateCommit();
console.log(depositDetails);

// // confirm if deposit address has been funded
// confirm if deposit address has been funded
const ready = await transaction.isReady(); //- true/false

if (ready || transaction.ready) {
// build transaction
transaction.build();
await transaction.build();

// sign transaction
const psbtHex = transaction.toHex();
const sig = wallet.signPsbt(psbtHex, { isRevealTx: true });
// console.log(JSON.stringify(sig, null, 2))
const signedTx = publisherWallet.signPsbt(transaction.toHex(), { isRevealTx: true });

// Broadcast transaction
const submittedTx = await wallet.relayTx(sig, "testnet");
console.log(submittedTx);
//{"txid": "<TX_ID>"}
const txId = await publisherWallet.relayTx(signedTx, network);
console.log({ txId });
}
}

async function mint() {
// Load wallet
const userWallet = new Ordit({
bip39: "<MNEMONIC PHRASE>",
network: "testnet"
});

const pubWallet = new Ordit({
bip39: "<MNEMONIC PHRASE>",
network: "testnet"
});

//set default taproot
userWallet.setDefaultAddress("taproot");
// pubWallet.setDefaultAddress("taproot");

// details of mint
const col = "04a0d2c4215607f2a16a5a458d0bd8e0528de0b7990bd9d52659d7d5c6263a54:0";
const sigMsg = `${col} el-01 1`; // COLLECTION_OUT INSCRIPTION_IID NONCE
const sig = pubWallet.signMessage(sigMsg);

pubWallet.setDefaultAddress("taproot");
//publish
const transaction = await Ordit.collection.mint({
collectionOutpoint: col,
// replace this w/ the resulting txId:index of above publish() fn
const collectionId = "";
const message = `${collectionId.split(":")[0]} el-01 1`; // COLLECTION_OUT INSCRIPTION_IID NONCE
const signature = publisherWallet.signMessage(message);

// publish
const transaction = await mintFromCollection({
network,
collectionOutpoint: collectionId,
inscriptionIid: "el-01",
nonce: 1,
publisherIndex: 0,
signature: sig,
signature,
publicKey: userWallet.publicKey,
destination: userWallet.selectedAddress,
changeAddress: userWallet.selectedAddress,
postage: 1000,
feeRate: 2,
mediaContent: 'Sample content',
mediaType: "text/plain",
outs: [{address: 'tb1pk6yxhcwzzjg9gwsumnlrh3l9q3ajxk657e7kqwmwpd8mklmnmehsrn3hu2', value: 1000}]
outputs: [],
});

const depositDetails = transaction.generateCommit();
const depositDetails = await transaction.generateCommit();
console.log(depositDetails);

// // confirm if deposit address has been funded
// confirm if deposit address has been funded
const ready = await transaction.isReady(); //- true/false

if (ready || transaction.ready) {
// build transaction
transaction.build();
await transaction.build();

// sign transaction
const psbtHex = transaction.toHex();
const sig = userWallet.signPsbt(psbtHex, { isRevealTx: true });
// console.log(JSON.stringify(sig, null, 2))
const signedTx = userWallet.signPsbt(transaction.toHex(), { isRevealTx: true });

// Broadcast transaction
const submittedTx = await userWallet.relayTx(sig, "testnet");
console.log(submittedTx);
//{"txid": "<TX_ID>"}
const txId = await userWallet.relayTx(signedTx, network);
console.log({ txId });
}
}

publish();
mint();
publish(); // comment this after collection is created
// mint(); // uncomment this after collection is created on chain using publish()
4 changes: 2 additions & 2 deletions examples/node/create-psbt.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ async function main() {
address: 'tb1p98dv6f5jp5qr4z2dtaljvwrhq34xrr8zuaqgv4ajf36vg2mmsruqt5m3lv',
outputs: [{
address: 'tb1qatkgzm0hsk83ysqja5nq8ecdmtwl73zwurawww',
cardinals: 1200
value: 1200
}],
network: 'testnet',
satsPerByte: 9,
satsPerByte: 2,
format: 'p2tr'
})

Expand Down
22 changes: 11 additions & 11 deletions packages/sdk/src/inscription/collection.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { GetWalletOptions, OrditApi, OrdTransaction, verifyMessage } from ".."
import { GetWalletOptions, Inscriber, OrditApi, verifyMessage } from ".."
import { Network } from "../config/types"

export async function publishCollection({
Expand Down Expand Up @@ -28,7 +28,7 @@ export async function publishCollection({
insc: inscriptions
}

return new OrdTransaction({ ...options, meta: collectionMeta })
return new Inscriber({ ...options, meta: collectionMeta })
}

export async function mintFromCollection(options: MintFromCollectionOptions) {
Expand Down Expand Up @@ -94,7 +94,7 @@ export async function mintFromCollection(options: MintFromCollectionOptions) {

meta.sig = options.signature

return new OrdTransaction({ ...options, meta })
return new Inscriber({ ...options, meta })
}

function validateInscriptions(inscriptions: CollectionInscription[] = []) {
Expand All @@ -110,9 +110,9 @@ function validateInscriptions(inscriptions: CollectionInscription[] = []) {
}

export type PublishCollectionOptions = Pick<GetWalletOptions, "safeMode"> & {
feeRate?: number
postage?: number
mediaType?: string
feeRate: number
postage: number
mediaType: string
mediaContent: string
destination: string
changeAddress: string
Expand All @@ -127,7 +127,7 @@ export type PublishCollectionOptions = Pick<GetWalletOptions, "safeMode"> & {
email?: string
address: string
}
network?: Network
network: Network
publicKey: string
outs?: Outputs
encodeMetadata?: boolean
Expand All @@ -141,9 +141,9 @@ export type CollectionInscription = {
}

export type MintFromCollectionOptions = Pick<GetWalletOptions, "safeMode"> & {
feeRate?: number
postage?: number
mediaType?: string
feeRate: number
postage: number
mediaType: string
mediaContent: string
destination: string
changeAddress: string
Expand All @@ -152,7 +152,7 @@ export type MintFromCollectionOptions = Pick<GetWalletOptions, "safeMode"> & {
nonce: number
publisherIndex: number
signature: string
network?: Network
network: Network
publicKey: string
outs?: Outputs
traits?: any
Expand Down
22 changes: 8 additions & 14 deletions packages/sdk/src/inscription/witness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,22 +56,16 @@ export function buildWitnessScript({ recover = false, ...options }: WitnessScrip
})
}

try {
if (recover) {
return bitcoin.script.compile([Buffer.from(options.xkey, "hex"), bitcoin.opcodes.OP_CHECKSIG])
}

return bitcoin.script.compile([
...baseStackElements,
...contentStackElements,
bitcoin.opcodes.OP_ENDIF,
...metaStackElements
])
} catch (error) {
//fail silently
if (recover) {
return bitcoin.script.compile([Buffer.from(options.xkey, "hex"), bitcoin.opcodes.OP_CHECKSIG])
}

return false
return bitcoin.script.compile([
...baseStackElements,
...contentStackElements,
bitcoin.opcodes.OP_ENDIF,
...metaStackElements
])
}

function opPush(str: string, encoding: BufferEncoding = "utf8") {
Expand Down
Loading

0 comments on commit 4b0e73a

Please sign in to comment.