Skip to content

Commit

Permalink
fix(sdk): improvements & fixes for v2.0.0 (#70)
Browse files Browse the repository at this point in the history
* fix: update input size for taproot

* fix: add output for recovery mode and update calculation

* refactor: update error message

* feta: add getInscriptionUTXO RPC call

* perf: replace getUnspents w/ getInscriptionUTXO

* feat: add data getter on all new classes

* fix: remove duplicate class members

* refactor: update examples to use new fns

* feat: add UTXOManager class

* fix: convert inscription id to specific format

* refactor: add missing filters to getInscriptions and relay fn

* fix: remove unnecessary check

* fix: remove unused imports

* fix: check inscription ownership

* revert: use previous implementation of GetInscriptions

* fix: format outpoint to id & revert ownership check
  • Loading branch information
iamcrazycoder authored Sep 27, 2023
1 parent eb8f19c commit 75adfb4
Show file tree
Hide file tree
Showing 22 changed files with 296 additions and 141 deletions.
13 changes: 8 additions & 5 deletions examples/node/build-psbt.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import { JsonRpcDatasource } from '@sadoprotocol/ordit-sdk'
import { Ordit } from '@sadoprotocol/ordit-sdk'
import { OrditApi, PSBTBuilder } from '@sadoprotocol/ordit-sdk'
import { PSBTBuilder } from '@sadoprotocol/ordit-sdk'

const network = 'testnet'
const wallet = new Ordit({
bip39: '<mnemonic>',
network: 'testnet'
network
})
wallet.setDefaultAddress('taproot')
const datasource = new JsonRpcDatasource({ network })

async function buildPSBT() {
const psbt = new PSBTBuilder({
address: wallet.selectedAddress,
feeRate: 2,
network: 'testnet',
network,
publicKey: wallet.publicKey,
outputs: [{
address: 'mwwTsmPhVcJzbW6dCeLVYoJQMraW1EeeuN',
Expand All @@ -22,8 +25,8 @@ async function buildPSBT() {
await psbt.prepare()

const hex = psbt.toHex()
const signature = wallet.signPsbt(hex)
const txId = await OrditApi.relayTx({ hex: signature, network: 'testnet' })
const signedTxHex = wallet.signPsbt(hex)
const txId = await datasource.relay({ hex: signedTxHex })

console.log({ txId })
}
Expand Down
11 changes: 7 additions & 4 deletions examples/node/collections.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { JsonRpcDatasource } from "@sadoprotocol/ordit-sdk";
import { Ordit, mintFromCollection, publishCollection } from "@sadoprotocol/ordit-sdk";

const mnemonic = "<MNEMONIC PHRASE>";
Expand All @@ -19,6 +20,8 @@ const publisherWallet = new Ordit({
userWallet.setDefaultAddress("taproot");
publisherWallet.setDefaultAddress("taproot");

const datasource = new JsonRpcDatasource({ network })

async function publish() {
const getPublisherLegacyAddress = () => {
publisherWallet.setDefaultAddress("legacy")
Expand Down Expand Up @@ -72,10 +75,10 @@ async function publish() {
await transaction.build();

// sign transaction
const signedTx = publisherWallet.signPsbt(transaction.toHex(), { isRevealTx: true });
const signedTxHex = publisherWallet.signPsbt(transaction.toHex(), { isRevealTx: true });

// Broadcast transaction
const txId = await publisherWallet.relayTx(signedTx, network);
const txId = await datasource.relay({ hex: signedTxHex });
console.log({ txId });
}
}
Expand Down Expand Up @@ -115,10 +118,10 @@ async function mint() {
await transaction.build();

// sign transaction
const signedTx = userWallet.signPsbt(transaction.toHex(), { isRevealTx: true });
const signedTxHex = userWallet.signPsbt(transaction.toHex(), { isRevealTx: true });

// Broadcast transaction
const txId = await userWallet.relayTx(signedTx, network);
const txId = await datasource.relay({ hex: signedTxHex });
console.log({ txId });
}
}
Expand Down
25 changes: 14 additions & 11 deletions examples/node/create-psbt.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,33 @@
import { JsonRpcDatasource } from '@sadoprotocol/ordit-sdk';
import { Ordit, ordit } from '@sadoprotocol/ordit-sdk'

async function main() {
const MNEMONIC = "<MNEMONIC>"; // Generated HD wallet seed phrase
const wallet = new Ordit({
bip39: MNEMONIC,
network: "testnet"
});
const MNEMONIC = "<MNEMONIC>"; // Generated HD wallet seed phrase
const network = "testnet"
const wallet = new Ordit({
bip39: MNEMONIC,
network
});
wallet.setDefaultAddress('taproot')

wallet.setDefaultAddress('taproot')
const datasource = new JsonRpcDatasource({ network })

async function main() {
const psbt = await ordit.transactions.createPsbt({
pubKey: '039ce27aa7666731648421004ba943b90b8273e23a175d9c58e3ec2e643a9b01d1',
address: 'tb1p98dv6f5jp5qr4z2dtaljvwrhq34xrr8zuaqgv4ajf36vg2mmsruqt5m3lv',
outputs: [{
address: 'tb1qatkgzm0hsk83ysqja5nq8ecdmtwl73zwurawww',
value: 1200
}],
network: 'testnet',
network,
satsPerByte: 2,
format: 'p2tr'
})

const signature = await wallet.signPsbt(psbt.hex)
const txResponse = await wallet.relayTx(signature, 'testnet')
const signedTxHex = await wallet.signPsbt(psbt.hex)
const txId = await datasource.relay({ hex: signedTxHex })

console.log("tx >>", txResponse)
console.log({ txId })
}

main()
28 changes: 16 additions & 12 deletions examples/node/inscribe.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,29 @@
import { Ordit } from "@sadoprotocol/ordit-sdk"
import { JsonRpcDatasource } from "@sadoprotocol/ordit-sdk";
import { Inscriber, Ordit } from "@sadoprotocol/ordit-sdk"

const MNEMONIC = "<MNEMONIC>"
const MNEMONIC = "<mnemonic>"
const network = "testnet"
const datasource = new JsonRpcDatasource({ network })

async function main() {
// init wallet
const wallet = new Ordit({
bip39: MNEMONIC,
network: "testnet"
network
});

wallet.setDefaultAddress('taproot')

// new inscription tx
const transaction = Ordit.inscription.new({
network: "testnet",
const transaction = new Inscriber({
network,
address: wallet.selectedAddress,
publicKey: wallet.publicKey,
changeAddress: wallet.selectedAddress,
destination: wallet.selectedAddress,
mediaContent: 'iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAAsTAAALEwEAmpwYAAADGElEQVR4nO2by04UQRSGvw34CjoGDAQ3XhDXRnTBAiG4ExMn8QlMmHh5ghE2OOMTsOPmgkSJuhiIuNCVvgFGRia6YFxoNPEGjClyOjlpZyKMU101dn1Jp5Pups7pw+mqv07VQCAQCARaTg9wDcgDc8AjYEXOc3I9C/TyH3EamAbKQO0Ah3n+HtBPmzIIlBq83DawAbwGXsp5Q67Xe74k7bUFR4CF2AvsAGtADjgLdDb42065n5Pnd2LtLAIZPOYSsKUc/grcB4412V43UAS+qDarwAgechPYVY4utPC/ZdqZV20bO7fwiLxy7jNw1ZKdcWk/sjWFB9xQDn0Azli2dwLYVDbv4Pib3xVH3ss4nwSmT6moz2EUR739lkr7UwnbP6k+h6qL0WFRpaFRby64EhsiE2Mw1tu7RI8OF5MyWlLjvGthclT8MP6sJqXta3IYkeIDReXTgG1j00reNqvwWk23ks0F28bKYshodZ94Jn69s2mkR6WambD4RE751mfLSFYZMbM2nxhQvl23rfm3gUP4RQfwU/y7a8vIrBh4i5+8Ef+MNrDCshgwFRwfeSX+PbYtgF7gJ8/FPzMiWGE57Rkwm/Y+IK9GgUaFTR9GgUlbRrJp1wG9baIEj9s0VE7zXCA+GzSzMB/oUrNBsw5hlX6VatannvukkGQ9wLeKUEZVhBL7LC+oiFsbc5uoCZ53VRUex31VeMlF6lXVuoCp0yeJWSH6JPY/AodxwIhaGaokWCPsUstjpvcfwyG3VRpWEsiE+NrgDB4wFVsdHrf4zUdpHx3fXa0N1ssEvT9gvsX7A+ZiO05m5OW9CsKo6hgjnVD8B8XYJSInGuejDm9M2fMuCBngQYM9QhOyf8BMXevRIfcnRNvH9wgt1entvQxCJJZWG+z6+gWsS2VpRc7rcr3e82t/ETneBgHR5gWZpdUOcGzKxGa/2t7rIET0SbFiUjrJJ5IBT6WTm5T7zc7n2yIIthkGvkkQfgCXSSHDIQiEIBhCJhCCsEfIBEIQ9giZwJ9iaYiUB+EhKWVIfqx1zrUjgUAggG/8BsfNc0SX+zvYAAAAAElFTkSuQmCC',
mediaType: "image/png",
feeRate: 15,
mediaContent: 'Hello World',
mediaType: "text/plain",
feeRate: 3,
meta: { // Flexible object: Record<string, any>
title: "Example title",
desc: "Lorem ipsum",
Expand All @@ -34,21 +38,21 @@ async function main() {
})

// generate deposit address and fee for inscription
const revealed = transaction.generateCommit();
const revealed = await transaction.generateCommit();
console.log(revealed) // deposit revealFee to address

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

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

// sign transaction
const signature = wallet.signPsbt(transaction.toHex(), { isRevealTx: true });
const signedTxHex = wallet.signPsbt(transaction.toHex(), { isRevealTx: true });

// Broadcast transaction
const tx = await wallet.relayTx(signature, "testnet");
const tx = await datasource.relay({ hex: signedTxHex });
console.log(tx);
}
}
Expand Down
22 changes: 13 additions & 9 deletions examples/node/instant-buy.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
import { JsonRpcDatasource } from '@sadoprotocol/ordit-sdk'
import { Ordit, InstantTradeBuyerTxBuilder, InstantTradeSellerTxBuilder } from '@sadoprotocol/ordit-sdk'

const BUYER_MNEMONIC = `<12-WORDS-PHRASE>`
const SELLER_MNEMONIC = `<12-WORDS-PHRASE>`
const network = "testnet"

// Initialise seller wallet
const sellerWallet = new Ordit({
bip39: SELLER_MNEMONIC,
network: 'testnet'
network
})
sellerWallet.setDefaultAddress('nested-segwit') // Switch to address that owns inscription

// Initialise buyer wallet
const buyerWallet = new Ordit({
bip39: BUYER_MNEMONIC,
network: 'testnet'
network
})

// Switch to address that has enough BTC to cover the sell price + network fees
buyerWallet.setDefaultAddress('taproot')

const datasource = new JsonRpcDatasource({ network })

async function createSellOrder() {
// replace w/ inscription outputpoint you'd like to sell, price, and address to receive sell proceeds
const instantTrade = new InstantTradeSellerTxBuilder({
network: 'testnet',
network,
address: sellerWallet.selectedAddress,
publicKey: sellerWallet.publicKey,
inscriptionOutpoint: '58434bd163e5b87c871e5b17c316a3cf141e0e10c3979f0b5ed2530d1d274040:1',
Expand All @@ -38,7 +42,7 @@ async function createSellOrder() {

async function createBuyOrder({ sellerPSBT }) {
const instantTrade = new InstantTradeBuyerTxBuilder({
network: 'testnet',
network,
address: buyerWallet.selectedAddress,
publicKey: buyerWallet.publicKey,
sellerPSBT,
Expand All @@ -47,17 +51,17 @@ async function createBuyOrder({ sellerPSBT }) {
await instantTrade.build()

const buyerPSBT = instantTrade.toHex()
const signedTx = buyerWallet.signPsbt(buyerPSBT)
const tx = await buyerWallet.relayTx(signedTx, 'testnet')
const signedTxHex = buyerWallet.signPsbt(buyerPSBT)
const txId = await datasource.relay({ hex: signedTxHex })

return tx
return txId
}

async function main() {
const signedSellerPSBT = await createSellOrder()
const tx = await createBuyOrder({ sellerPSBT: signedSellerPSBT })
const txId = await createBuyOrder({ sellerPSBT: signedSellerPSBT })

console.log(tx)
console.log({ txId })
}

;(async() => {
Expand Down
10 changes: 0 additions & 10 deletions examples/node/read.js

This file was deleted.

28 changes: 28 additions & 0 deletions examples/node/split-utxo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { JsonRpcDatasource } from "@sadoprotocol/ordit-sdk";
import { Ordit } from "@sadoprotocol/ordit-sdk";
import { UTXOManager } from "@sadoprotocol/ordit-sdk";

const network = 'testnet'
const wallet = new Ordit({
bip39: '<mnemonic>',
network
})
wallet.setDefaultAddress('taproot')

async function main() {
const datasource = new JsonRpcDatasource({ network })
const utxoManager = new UTXOManager({
address: wallet.selectedAddress,
network,
publicKey: wallet.publicKey,
feeRate: 3
})

await utxoManager.splitUTXOForInstantTrade()
const hex = utxoManager.toHex()
const signedTxHex = wallet.signPsbt(hex)
const txId = await datasource.relay({ hex: signedTxHex })
console.log({ txId })
}

main()
4 changes: 2 additions & 2 deletions packages/sdk/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ import { decodeObject } from "../utils"
import { rpc } from "./jsonrpc"
import {
FetchInscriptionOptions,
FetchInscriptionsOptions,
FetchSpendablesOptions,
FetchTxOptions,
FetchTxResponse,
FetchUnspentUTXOsOptions,
FetchUnspentUTXOsResponse,
GetBalanceOptions,
GetInscriptionsOptions,
RelayTxOptions
} from "./types"

Expand Down Expand Up @@ -118,7 +118,7 @@ export class OrditApi {
}
}

static async fetchInscriptions({ outpoint, network = "testnet", decodeMetadata = true }: FetchInscriptionsOptions) {
static async fetchInscriptions({ outpoint, network = "testnet", decodeMetadata = true }: GetInscriptionsOptions) {
if (!outpoint) {
throw new Error("Invalid options provided.")
}
Expand Down
15 changes: 12 additions & 3 deletions packages/sdk/src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Transaction as BTCTransaction } from "bitcoinjs-lib"
import { Network } from "../config/types"
import { Rarity } from "../inscription/types"
import { Transaction, UTXO } from "../transactions/types"
import { RequireAtLeastOne } from "../utils/types"

export interface FetchUnspentUTXOsOptions {
address: string
Expand Down Expand Up @@ -35,10 +36,18 @@ export interface FetchTxResponse {
rawTx?: BTCTransaction
}

export interface FetchInscriptionsOptions {
outpoint: string
network?: Network
export type GetInscriptionsOptions = RequireAtLeastOne<{
creator?: string
owner?: string
mimeType?: string
mimeSubType?: string
outpoint?: string
}> & {
sort?: "asc" | "desc"
limit?: number
next?: string | null
decodeMetadata?: boolean
network?: Network
}

export interface FetchInscriptionOptions {
Expand Down
17 changes: 12 additions & 5 deletions packages/sdk/src/fee/FeeEstimator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@ import { MAXIMUM_FEE } from "../constants"
import { FeeEstimatorOptions } from "./types"

export default class FeeEstimator {
protected fee = 0
protected feeRate: number
protected network: Network
protected psbt: Psbt
protected witness?: Buffer[] = []
protected fee = 0

private virtualSize = 0
private weight = 0
protected virtualSize = 0
protected weight = 0

constructor({ feeRate, network, psbt, witness }: FeeEstimatorOptions) {
if (feeRate < 0 || !Number.isSafeInteger(feeRate)) {
Expand All @@ -26,6 +25,14 @@ export default class FeeEstimator {
this.psbt = psbt || new Psbt({ network: getNetwork(this.network) })
}

get data() {
return {
fee: this.fee,
virtualSize: this.virtualSize,
weight: this.weight
}
}

private sanityCheckFee() {
if (this.fee > MAXIMUM_FEE) {
throw new Error("Error while calculating fees")
Expand Down Expand Up @@ -122,7 +129,7 @@ export default class FeeEstimator {
private getBaseSizeByType(type: AddressFormats) {
switch (type) {
case "taproot":
return { input: 41, output: 43, txHeader: 10.5, witness: 66 } // witness size is different for non-default sigHash
return { input: 41.5, output: 43, txHeader: 10.5, witness: 66 } // witness size is different for non-default sigHash

case "segwit":
return { input: 41, output: 31, txHeader: 10.5, witness: 105 }
Expand Down
1 change: 1 addition & 0 deletions packages/sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,6 @@ export * from "./signatures"
export * from "./transactions"
export { PSBTBuilder } from "./transactions/PSBTBuilder"
export * from "./utils"
export { UTXOManager } from "./utxos"
export * from "./wallet"
export { Ordit } from "./wallet/Ordit"
Loading

0 comments on commit 75adfb4

Please sign in to comment.