-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnft-create-the-hard-way.ts
329 lines (268 loc) · 12 KB
/
nft-create-the-hard-way.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import { URLPayload } from "avalanche/dist/utils";
import { Avalanche, BinTools, BN } from "avalanche"
import { Buffer } from "buffer/";
import {
AmountOutput,
AVMAPI,
AVMConstants,
CreateAssetTx,
InitialStates,
KeyChain,
MinterSet,
NFTMintOperation,
NFTMintOutput,
NFTTransferOperation,
NFTTransferOutput,
OperationTx,
SECPTransferInput,
SECPTransferOutput,
TransferableInput,
TransferableOperation,
TransferableOutput,
Tx,
UnsignedTx,
UTXO,
UTXOSet
} from "avalanche/dist/apis/avm"
import { OutputOwners } from "avalanche/dist/common"
const sleep = (ms: number): Promise<unknown> => {
return new Promise(resolve => setTimeout(resolve, ms))
}
// This small helper function will go through the UTXOs present in the `utxoSet`. It will look for one with
// a specific `txid`, and a specific `outputType` .
const getUTXOIDs = (utxoSet: UTXOSet, txid: string, outputType: number = AVMConstants.SECPMINTOUTPUTID): string[] => {
const utxoids: string[] = utxoSet.getUTXOIDs()
let result: string[] = []
for (let index: number = 0; index < utxoids.length; ++index) {
if (utxoids[index].indexOf(txid.slice(0, 10)) !== -1 && utxoSet.getUTXO(utxoids[index]) && utxoSet.getUTXO(utxoids[index]).getOutput().getOutputID() === outputType) {
if (result.length === 0) {
result.push(utxoids[index])
}
}
}
return result
}
// Setting up the connection to the AvalancheGo Node
const ip: string = "localhost"
const protocol: string = "http"
const networkID: number = 12345
const port: number = 9650
const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID)
const bintools: BinTools = BinTools.getInstance()
const avm: AVMAPI = avalanche.XChain()
const blockchainID: Buffer = bintools.cb58Decode(avm.getBlockchainID())
const xKeychain: KeyChain = avm.keyChain()
const imgs = [
"https://i.ibb.co/hs6CW8j/brown-Copy.png",
"https://i.ibb.co/yQ8hfwB/turquese.png",
"https://i.ibb.co/RQpFfYP/white.png",
"https://i.ibb.co/pZyYF1M/yellow.png",
"https://i.ibb.co/HHyZcvm/grey.png",
"https://i.ibb.co/wyQk605/green.png",
"https://i.ibb.co/qM5Hs5t/blue-Copy.png",
"https://i.ibb.co/ydXY8bD/pink.png",
"https://i.ibb.co/mqfx1NJ/strong-red.png"
]
const memos = [];
// Here we will convert the url to a base58 payload .
for (let img of imgs) {
memos.push((new URLPayload(img)).getPayload())
console.log(bintools.bufferToB58(bintools.addChecksum(new URLPayload(Buffer.from(img)).getPayload())))
}
// PKey on local network containing lot of AVAX
xKeychain.importKey("PrivateKey-ewoqjP7PxY4yr3iLTpLisriqt94hdyDFNgchSxGGztUrTXtNN")
// Fetch all addresses (buffer format) linked to the Pkey
const xAddresses: Buffer[] = avm.keyChain().getAddresses();
// Readable format for address
const xAddressStrings: string[] = avm.keyChain().getAddressStrings()
console.log(xAddressStrings)
const locktime: BN = new BN(0)
const threshold: number = 1
const mstimeout: number = 2000
async function selectUtxoWithEnoughAvax() {
// We fetch the UTXOs of the current address
let {utxos: utxoSet} = await avm.getUTXOs(xAddressStrings, 'X', 2048)
// Here we select one UTXO where there is enough AVAX to pay for the fee .
let utxos: UTXO[] = utxoSet.getAllUTXOs().filter(u => u.getOutput().getTypeName() === 'SECPTransferOutput' && u.getOutput().getOutputID() === 7)
let utxo: UTXO;
for (let aUtxo of utxos) {
let output: AmountOutput = aUtxo.getOutput() as AmountOutput
let amt: BN = output.getAmount().clone()
if (amt > new BN(100000000)) {
utxo = aUtxo
break;
}
}
return utxo;
}
async function createNewNFTAsset(assetID, createFee) {
let ins: TransferableInput[] = []
let outs: TransferableOutput[] = []
await substractFee(outs, assetID, createFee);
let utxo = await selectUtxoWithEnoughAvax();
let output: AmountOutput = utxo.getOutput() as AmountOutput
let amt: BN = output.getAmount().clone()
let txid: Buffer = utxo.getTxID()
let outputidx: Buffer = utxo.getOutputIdx()
let secpInput: SECPTransferInput = new SECPTransferInput(amt)
secpInput.addSignatureIdx(0, xAddresses[0])
// We create the transferable input, pointing to the Tx where we have enough AVAX for the fee .
let transferableInput: TransferableInput = new TransferableInput(txid, outputidx, assetID, secpInput)
ins.push(transferableInput)
// Some info about our new Asset
const name: string = "AVHAT"
const symbol: string = "HAT"
const initialStates: InitialStates = new InitialStates()
// Not sure what the 'groupID' represent .
const groupID: number = 42
// Create the minter set .
// It will create X amount of UTXO with `NFTMINTOUTPUTID` as type .
// Those can be consumed by address present in the minterSet in a nftMint operation .
for (var i = 0; i < 100; i++) {
const minterSet: MinterSet = new MinterSet(1, xAddresses)
// Threshold represent the number of signatures we need in order to mint a new asset .
const nftMintOutput: NFTMintOutput = new NFTMintOutput(
groupID,
minterSet.getMinters(),
locktime,
minterSet.getThreshold()
)
initialStates.addOutput(nftMintOutput, AVMConstants.NFTFXID)
}
const denomination: number = 0
const createAssetTx: CreateAssetTx = new CreateAssetTx(networkID, blockchainID, outs, ins, Buffer.from("AVHAT"), name, symbol, denomination, initialStates)
let unsignedTx: UnsignedTx = new UnsignedTx(createAssetTx)
let tx: Tx = unsignedTx.sign(xKeychain)
let id: string = await avm.issueTx(tx)
console.log(id)
await sleep(mstimeout)
return id;
}
async function substractFee(outs, assetID, fee) {
let result: any = await avm.getBalance(xAddressStrings[0], bintools.cb58Encode(assetID))
let balance = new BN(result.balance)
let avaxAmount = balance.sub(fee)
let secpOutput = new SECPTransferOutput(avaxAmount, xAddresses, locktime, threshold)
let transferableOutput = new TransferableOutput(assetID, secpOutput)
outs.push(transferableOutput)
}
async function mintNFT(assetID, fee, groupID: number, id: string, memo: Buffer) {
let ins: TransferableInput[] = []
let outs: TransferableOutput[] = []
// Again here we fetch the fee, create the output which will contain the balance - fee .
await substractFee(outs, assetID, fee);
// ToDo Still no clue what 'groupID' represent exactly here .
console.log(`PAYLOAD - ${bintools.bufferToB58(memo)}`)
const nftMintOperation: NFTMintOperation = new NFTMintOperation(groupID, memo, [new OutputOwners(xAddresses, locktime, threshold)])
let {utxos: utxoSet} = await avm.getUTXOs(xAddressStrings)
let utxo = await selectUtxoWithEnoughAvax();
let output: AmountOutput = utxo.getOutput() as AmountOutput
let amt: BN = output.getAmount().clone()
let txid: Buffer = utxo.getTxID()
let outputidx: Buffer = utxo.getOutputIdx()
let secpInput: SECPTransferInput = new SECPTransferInput(amt)
secpInput.addSignatureIdx(0, xAddresses[0])
// We create the transferable input, pointing to the Tx where we have enough AVAX for the fee .
let transferableInput: TransferableInput = new TransferableInput(txid, outputidx, assetID, secpInput)
ins.push(transferableInput)
let utxoids: string[] = getUTXOIDs(utxoSet, id, AVMConstants.NFTMINTOUTPUTID)
utxo = utxoSet.getUTXO(utxoids[0])
let out: NFTTransferOutput = utxo.getOutput() as NFTTransferOutput
let spenders: Buffer[] = out.getSpenders(xAddresses)
spenders.forEach((spender: Buffer) => {
const idx: number = out.getAddressIdx(spender)
nftMintOperation.addSignatureIdx(idx, spender)
})
let ops: TransferableOperation[] = []
let transferableOperation: TransferableOperation = new TransferableOperation(utxo.getAssetID(), utxoids, nftMintOperation)
ops.push(transferableOperation)
let operationTx: OperationTx = new OperationTx(networkID, blockchainID, outs, ins, Buffer.from("AVHAT"), ops)
let unsignedTx = new UnsignedTx(operationTx)
let tx = unsignedTx.sign(xKeychain)
let mint_tx_id = await avm.issueTx(tx);
let tx_status = await avm.getTxStatus(mint_tx_id);
while (tx_status !== 'Accepted') {
tx_status = await avm.getTxStatus(mint_tx_id);
}
await sleep(mstimeout)
return mint_tx_id;
}
async function transferNFT(assetID, fee, mint_tx_id) {
let ins: TransferableInput[] = []
let outs: TransferableOutput[] = []
let ops: TransferableOperation[] = []
let result: any = await avm.getBalance(xAddressStrings[0], bintools.cb58Encode(assetID))
let balance = new BN(result.balance)
let avaxAmount = balance.sub(fee)
let secpOutput = new SECPTransferOutput(avaxAmount, xAddresses, locktime, threshold)
let transferableOutput = new TransferableOutput(assetID, secpOutput)
outs.push(transferableOutput)
let {utxos: utxoSet} = await avm.getUTXOs(xAddressStrings)
let utxo = await selectUtxoWithEnoughAvax();
let output: AmountOutput = utxo.getOutput() as AmountOutput
let amt: BN = output.getAmount().clone()
let txid: Buffer = utxo.getTxID()
let outputidx: Buffer = utxo.getOutputIdx()
let secpInput: SECPTransferInput = new SECPTransferInput(amt)
secpInput.addSignatureIdx(0, xAddresses[0])
// We create the transferable input, pointing to the Tx where we have enough AVAX for the fee .
let transferableInput: TransferableInput = new TransferableInput(txid, outputidx, assetID, secpInput)
ins.push(transferableInput)
let utxoids = getUTXOIDs(utxoSet, mint_tx_id, AVMConstants.NFTXFEROUTPUTID)
utxo = utxoSet.getUTXO(utxoids[0])
let out = utxo.getOutput() as NFTTransferOutput
let spenders = out.getSpenders(xAddresses)
// Address to which we will send the newly minted NFT
const xaddy: Buffer = bintools.stringToAddress("X-local18jma8ppw3nhx5r4ap8clazz0dps7rv5u00z96u")
const outbound: NFTTransferOutput = new NFTTransferOutput(
out.getGroupID(), out.getPayload(), [xaddy], locktime, threshold,
)
const op: NFTTransferOperation = new NFTTransferOperation(outbound)
spenders.forEach((spender: Buffer) => {
const idx: number = out.getAddressIdx(spender)
op.addSignatureIdx(idx, spender)
})
const xferop: TransferableOperation = new TransferableOperation(utxo.getAssetID(), [utxoids[0]], op)
ops.push(xferop)
let operationTx = new OperationTx(networkID, blockchainID, outs, ins, memos[0], ops)
let unsignedTx = new UnsignedTx(operationTx)
let tx = unsignedTx.sign(xKeychain)
let new_id = await avm.issueTx(tx)
let tx_status = await avm.getTxStatus(new_id);
while (tx_status !== 'Accepted') {
console.log(`Waiting for MintTx -- ${tx_status} -- ${new_id}`)
await sleep(mstimeout)
tx_status = await avm.getTxStatus(new_id);
}
console.log(`TRF NFT TX ID ${new_id}`)
await sleep(mstimeout)
}
const main = async (): Promise<any> => {
// ===========================================
// First we will create an asset for our NFT .
// ===========================================
let mintTxs = [];
const assetID: Buffer = await avm.getAVAXAssetID()
let trffee: BN = avm.getTxFee()
let createFee: BN = avm.getCreationTxFee()
const nft_id = await createNewNFTAsset(assetID, createFee);
const groupID: number = 42
// Now we can Mint our NFT .
for (let memo of memos) {
console.log('Minting a new NFT !!!!!');
const mint_tx_id = await mintNFT(assetID, trffee, groupID, nft_id, memo);
mintTxs.push(mint_tx_id);
console.log(`MintNFTAsset tx id -- ${mint_tx_id}`)
}
for (let mintTx of mintTxs) {
console.log('Now we can transfer it !!!!')
try {
await transferNFT(assetID, trffee, mintTx);
} catch (e) {
console.error(`Transfer of ${mintTx} failed .`)
console.error(e)
}
console.log('============================== \n')
}
}
main()