Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Distribute NFT child tokens with burning the qty=1 parent ones #3

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions faucet_utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { BITBOX } from "bitbox-sdk";
import * as slpjs from "slpjs";
import { BchdNetwork, BchdValidator } from "slpjs";
import { BigNumber } from "bignumber.js";

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

export class FaucetUtils {
public network: BchdNetwork;

constructor (bitbox: BITBOX, validator: BchdValidator) {
this.network = new BchdNetwork({ BITBOX: bitbox, validator, logger: console, client: validator.client });
}

public async nftTokenSend(tokenId: string, inputUtxos: slpjs.SlpAddressUtxoResult[], tokenReceiverAddress: string, paymentAddress: string, paymentAddressWif: string): Promise<string> {
let burnUtxo: slpjs.SlpAddressUtxoResult | undefined = undefined;
inputUtxos.forEach((txo) => {
if (!burnUtxo && txo.slpUtxoJudgement === 'SLP_TOKEN' && txo.slpUtxoJudgementAmount.isEqualTo(1)) {
burnUtxo = txo;
}
})
// ---[ TODO: optimize this part to send both transactions with one call ]---
if (!burnUtxo) {
const burnTxHex = await this.network.txnHelpers.simpleTokenSend({
tokenId,
sendAmounts: [ new BigNumber(1) ],
inputUtxos,
tokenReceiverAddresses: [ paymentAddress ],
changeReceiverAddress: paymentAddress
})
const burnTxId: string = await this.network.sendTx(burnTxHex);
console.log(`burn tx: ${burnTxId}`);
console.log(`wait sync...`);
await sleep(3000);
}

const balances: slpjs.SlpBalancesResult = (await this.network.getAllSlpBalancesAndUtxos(paymentAddress) as slpjs.SlpBalancesResult);
balances.slpTokenUtxos[tokenId].forEach((txo) => {
if (!burnUtxo && txo.slpUtxoJudgementAmount.isEqualTo(1)) {
burnUtxo = txo;
}
});
if (!burnUtxo) throw new Error('No token ready for burn');

const inputs = [burnUtxo, ...balances!.nonSlpUtxos] as slpjs.SlpAddressUtxoResult[];
inputs.forEach((j) => j.wif = paymentAddressWif);

const name = process.env.NFTNAME! || "SLP Faucet NFT";
const ticker = process.env.NFTTICKER! || "SFNFT";
const documentUri: string|null = process.env.DOCUMENTURI || null;
const documentHash: Buffer|null = process.env.DOCUMENTHASH ? Buffer.from(process.env.DOCUMENTHASH, 'hex') : null;

const genesisTxHex = this.network.txnHelpers.simpleNFT1ChildGenesis({
nft1GroupId: tokenId,
tokenName: name,
tokenTicker: ticker,
documentUri,
documentHash,
tokenReceiverAddress: tokenReceiverAddress,
bchChangeReceiverAddress: paymentAddress,
inputUtxos: inputs
})
// console.log(`genesis hex: ${JSON.stringify(genesisTxHex, null, 2)}`)
const burn = {
tokenId: Buffer.from(tokenId, 'hex'),
tokenType: 129,
amount: '1',
outpointHash: Buffer.from(Buffer.from(burnUtxo!.txid, 'hex').reverse()),
outpointVout: burnUtxo!.vout
}

const genesisTxId = await this.network.sendTx(genesisTxHex, [burn]);
console.log('NFT1 Child GENESIS txn complete: ', genesisTxId);
return genesisTxId;
}
}
2 changes: 1 addition & 1 deletion server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ app.post("/", async (req, res) => {
let inputs: slpjs.SlpAddressUtxoResult[] = [];
inputs = inputs.concat(changeAddr.balance.slpTokenUtxos[process.env.TOKENID!]).concat(changeAddr.balance.nonSlpUtxos);
inputs.map((i) => i.wif = slpFaucet.wifs[changeAddr.address]);
sendTxId = await slpFaucet.simpleTokenSend(process.env.TOKENID!, new BigNumber(faucetQty), inputs, address, changeAddr.address);
sendTxId = await slpFaucet.tokenSend(process.env.TOKENID!, new BigNumber(faucetQty), inputs, address, changeAddr.address);
} catch (error) {
console.log(error);
res.render("index", { txid: null, error: "Server error." });
Expand Down
8 changes: 7 additions & 1 deletion slpfaucet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import { BITBOX } from "bitbox-sdk";
import { GrpcClient } from "grpc-bchrpc-node";
import * as slpjs from "slpjs";
import { BchdNetwork, BchdValidator, Utils } from "slpjs";
import { FaucetUtils } from "./faucet_utils";

const bitbox = new BITBOX();
const client = new GrpcClient({url: "bchd.ny1.simpleledger.io" });
const validator = new BchdValidator(client, console);
const faucetUtils = new FaucetUtils(bitbox, validator)

export class SlpFaucetHandler {
public addresses: string[];
Expand Down Expand Up @@ -144,8 +146,12 @@ export class SlpFaucetHandler {
throw Error("There are no addresses with sufficient balance");
}

public async simpleTokenSend(tokenId: string, sendAmount: BigNumber, inputUtxos: slpjs.SlpAddressUtxoResult[], tokenReceiverAddresses: string | string[], changeReceiverAddress: string): Promise<string> {
public async tokenSend(tokenId: string, sendAmount: BigNumber, inputUtxos: slpjs.SlpAddressUtxoResult[], tokenReceiverAddresses: string | string[], changeReceiverAddress: string): Promise<string> {
await this.increaseChainLength();
if (process.env.NFT!.toLowerCase() === 'yes') {
const receiverAddress = (typeof tokenReceiverAddresses === 'string') ? tokenReceiverAddresses : tokenReceiverAddresses[0];
return await faucetUtils.nftTokenSend(tokenId, inputUtxos, receiverAddress, changeReceiverAddress, this.wifs[changeReceiverAddress]);
}
return await this.network.simpleTokenSend(tokenId, sendAmount, inputUtxos, tokenReceiverAddresses, changeReceiverAddress);
}

Expand Down