-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathutils.ts
More file actions
492 lines (394 loc) · 18 KB
/
Copy pathutils.ts
File metadata and controls
492 lines (394 loc) · 18 KB
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
import { Command } from "commander"
import ora from "ora"
import inquirer from "inquirer"
import fs from "fs"
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate"
import { GasPrice } from "@cosmjs/stargate";
import PromisePool from '@supercharge/promise-pool';
import * as ethUtil from "ethereumjs-util";
import axios from "axios"
import { getChainConfig } from "./lighthouse"
import chalk from "chalk"
import Web3 from "web3"
import ERC2981Abi from "./contracts/erc2981_lighthouse_edition.abi"
export const command_utils = async (root: Command) => {
root
.command("associate-evm")
.description("Associate cosmwasm wallet to evm (seiv2)")
.action(async () => {
let { privateKey, rpc_evm } = await getChainConfig(true)
let spinner = ora("Associating wallet to EVM").start()
const privateKeyBuffer = Buffer.from(privateKey, "hex");
const emptyData = Buffer.alloc(32);
const signature = ethUtil.ecsign(emptyData, privateKeyBuffer);
const { r, s, v } = signature;
const compactV = Number(v) - 27;
let signed = {
r: ethUtil.bufferToHex(r),
s: ethUtil.bufferToHex(s),
v: `${compactV}`,
};
await axios.post(rpc_evm, {
id: 1,
jsonrpc: "2.0",
method: "sei_associate",
params: [{
...signed,
}]
}, {
headers: {
'accept': 'application/json',
'content-type': 'application/json'
}
})
spinner.succeed("Wallet associated to EVM")
})
root
.command("snapshot")
.description("Snapshot holders of a collection")
.argument("<collection>")
.option('-s --supply <supply>', 'Supply of the collection')
.option('-so --start-token-id <token_id>', 'Start token ID of the collection')
.option('-e, --exclude-contracts', 'Exclude contract addresses')
.option('-o, --output <file>', 'Output file name')
.option('-c, --count', 'Output how many tokens each holder owns')
.option('-d, --duplicate', 'Output duplicate holders', false)
.option('-st, --show-token-id', 'Show token ID', false)
.action(async (collection, options) => {
let spinner = ora("Fetching holders").start();
let { wallet, rpc_wasm } = await getChainConfig()
var client = await SigningCosmWasmClient.connectWithSigner(rpc_wasm, wallet, {
gasPrice: GasPrice.fromString(options.gasPrice ? options.gasPrice + "usei" : "0.1usei")
})
let numTokens;
let startTokenId = 1;
if (options.supply !== "auto") {
numTokens = parseInt(options.supply);
if (options.startTokenId) {
options.startTokenId = parseInt(options.startTokenId);
}
} else {
let numTokensResult = await client.queryContractSmart(collection, {
num_tokens: {}
});
numTokens = parseInt(numTokensResult.count);
}
try {
if (!options.startTokenId) {
await client.queryContractSmart(collection, {
owner_of: { token_id: '0' }
});
startTokenId = 0; // token ID 0 exists, start from 0
}
} catch (error) {
// assuming an error means Token ID 0 does not exist
}
const { results, errors } = await PromisePool
.withConcurrency(10)
.for([...Array(numTokens).keys()].map(i => String(i + startTokenId)))
.process(async token_id => {
try {
let result = await client.queryContractSmart(collection, {
owner_of: { token_id }
});
return result.owner;
} catch (error) {
console.error(`Error fetching owner for token ${token_id}:`, error);
return false;
}
});
let owners = results.filter(o => o !== false);
if (options.excludeContracts) {
owners = owners.filter(o => o.length <= 42);
}
spinner.succeed("Holders fetched");
let outputData = '';
if (options.count) {
const ownerCounts = owners.reduce((acc, owner) => {
acc[owner] = (acc[owner] || 0) + 1;
return acc;
}, {});
outputData = Object.entries(ownerCounts).map(([owner, count]) => `${owner}: ${count}`).join('\n');
} else if (!options.duplicate) {
owners = owners.filter((o, i, arr) => arr.indexOf(o) === i);
outputData = owners.join('\n');
} else {
if (options.showTokenId) {
owners = owners.map((o, i) => `${o} - ${i + startTokenId}`);
}
outputData = owners.join('\n');
}
let outputFileName = options.output;
if (!outputFileName) {
const answers = await inquirer.prompt([{
type: 'input',
name: 'file',
message: 'Enter file name to save snapshot to',
default: "owners.txt"
}])
outputFileName = answers.file
}
fs.writeFileSync(outputFileName, outputData)
console.log(`Snapshot saved to ${outputFileName}`);
});
root
.command("ownerof")
.description("Get the owner of an NFT(s)")
.argument("<collection>", "Collection address")
.argument("<token_ids>", "Token ID(s) separated by commas")
.action(async (collection, token_ids) => {
let spinner = ora("Fetching owner information").start()
let { rpc_wasm } = await getChainConfig()
const client = await SigningCosmWasmClient.connect(rpc_wasm)
let owners = []
for (let token_id of token_ids.split(",")) {
let result = await client.queryContractSmart(collection, {
owner_of: {
token_id
}
})
owners.push(result.owner)
}
spinner.succeed("Owners fetched")
console.log(owners.join("\n"))
//ask to save to file
const answers = await inquirer.prompt([{
type: 'confirm',
name: 'save',
message: 'Save owners to a file?',
default: false
}])
if (answers.save) {
const answers = await inquirer.prompt([{
type: 'input',
name: 'file',
message: 'Enter file name',
default: "owners.txt"
}])
fs.writeFileSync(answers.file, owners.join("\n"))
}
})
root
.command("minterof")
.description("Get the minter of token(s)")
.argument("<collection>", "Collection address")
.argument("<token_ids>", "Token ID(s) separated by commas")
.action(async (collection, token_ids) => {
let spinner = ora("Fetching Minter information").start()
let { lighthouse, rpc_wasm } = await getChainConfig()
const client = await SigningCosmWasmClient.connect(rpc_wasm)
let minters = []
for (let token_id of token_ids.split(",")) {
let result = await client.queryContractSmart(lighthouse, {
get_minter_of: {
collection,
token_id
}
})
minters.push({ token_id, minter: result })
}
spinner.succeed("Minters fetched")
console.log(minters.map((minter: any) => minter.token_id + " " + minter.minter).join("\n"))
//ask to save to file
const answers = await inquirer.prompt([{
type: 'confirm',
name: 'save',
message: 'Save minters to a file?',
default: false
}])
if (answers.save) {
const answers = await inquirer.prompt([{
type: 'input',
name: 'file',
message: 'Enter file name',
default: "minters.txt"
}])
fs.writeFileSync(answers.file, minters.map((minter: any) => minter.token_id + " " + minter.minter).join("\n"))
}
})
root
.command("mintersof")
.description("Get all minters of a collection")
.argument("<collection>", "Collection address")
.option("--delay <delay>", "Delay between requests (default: 100ms)")
.action(async (collection, options) => {
let spinner = ora("Fetching Minter information").start()
let { lighthouse, rpc_wasm } = await getChainConfig()
const client = await SigningCosmWasmClient.connect(rpc_wasm)
let collectionData = await client.queryContractSmart(lighthouse, { get_collection: { collection } })
let minters = []
for (let i = 0; i < collectionData.supply; i++) {
try {
let result = await client.queryContractSmart(lighthouse, {
get_minter_of: {
collection,
token_id: (i + collectionData.start_order).toString()
}
})
minters.push({ token_id: (i + collectionData.start_order).toString(), minter: result })
await new Promise(r => setTimeout(r, options.delay ? options.delay : 100));
} catch (error) {
console.error(`Error fetching minter for token ${i + collectionData.start_order}:`, error);
}
}
spinner.succeed("Minters fetched")
console.log(minters.map((minter: any) => minter.token_id + " " + minter.minter).join("\n"))
//ask to save to file
const answers = await inquirer.prompt([{
type: 'confirm',
name: 'save',
message: 'Save minters to a file?',
default: false
}])
if (answers.save) {
const answers = await inquirer.prompt([{
type: 'input',
name: 'file',
message: 'Enter file name',
default: "minters.txt"
}])
fs.writeFileSync(answers.file, minters.map((minter: any) => minter.token_id + " " + minter.minter).join("\n"))
}
})
root
.command("view-nft")
.description("View NFT information")
.argument("<collection>", "Collection address")
.argument("<token_id>", "Token ID")
.action(async (collection, token_id) => {
let spinner = ora("Fetching NFT information").start()
let { rpc_wasm } = await getChainConfig()
const client = await SigningCosmWasmClient.connect(rpc_wasm)
let result = await client.queryContractSmart(collection, {
nft_info: {
token_id
}
})
spinner.succeed("NFT fetched")
console.log(result)
})
root
.command("transfer-nft")
.description("Transfer NFT")
.arguments("<collection> <token_id> <to>")
.option("-g --gas-price <gas_price>", "Gas price to use for transaction (default: 0.1)")
.action(async (collection, tokenId, to, options) => {
let {wallet, rpc_wasm } = await getChainConfig()
const [firstAccount] = await wallet.getAccounts()
const client = await SigningCosmWasmClient.connectWithSigner(rpc_wasm, wallet, {
gasPrice: GasPrice.fromString(options.gasPrice ? options.gasPrice + "usei" : "0.1usei")
})
let spinner = ora("Transferring NFT").start()
const transferMsg = {
transfer_nft: {
recipient: to,
token_id: tokenId
}
}
const txReceipt = await client.execute(firstAccount.address, collection, transferMsg, "auto", "",)
spinner.succeed("NFT transferred")
console.log("Transaction hash: " + chalk.green(txReceipt.transactionHash))
})
root
.command("transfer-evm-nft")
.description("Transfer NFT")
.arguments("<collection> <token_id> <to>")
.action(async (collection, tokenId, to) => {
let {privateKey, rpc_evm } = await getChainConfig()
const web3 = new Web3(rpc_evm);
const contractInstance = new web3.eth.Contract(ERC2981Abi, collection);
const accountAddress = web3.eth.accounts.privateKeyToAccount("0x" + privateKey).address;
const data = contractInstance.methods.transferFrom(accountAddress, to, tokenId).encodeABI();
const signedTxUpdate = await web3.eth.accounts.signTransaction(
{
from: accountAddress,
to: collection,
data,
gas: await contractInstance.methods.transferFrom(accountAddress, to, tokenId).estimateGas({ from: accountAddress }),
maxPriorityFeePerGas: web3.utils.toWei('2', 'gwei'),
maxFeePerGas: web3.utils.toWei('100', 'gwei'),
},
privateKey
);
let spinner = ora("Transferring NFT").start()
const receipt =await web3.eth.sendSignedTransaction(signedTxUpdate.rawTransaction);
spinner.succeed("NFT transferred")
console.log("Transaction hash: " + chalk.green(receipt.transactionHash))
})
root
.command("mint")
.description("Mint new NFTs from an existing NFT collection. Only free minting is supported.")
.argument("<collection>")
.argument("<group_name>", "Mint from a specific group")
.argument("<amount>", "Amount of NFTs to mint")
.option("-g --gas-price <gas_price>", "Gas price to use for transaction (default: 0.1)")
.action(async (collection, groupName, amount, answers) => {
if (groupName) {
console.log("Minting from group: " + groupName)
} else {
console.log(chalk.red("You must specify a group to mint from"))
return
}
let {wallet, lighthouse, rpc_wasm } = await getChainConfig()
const [firstAccount] = await wallet.getAccounts()
const client = await SigningCosmWasmClient.connectWithSigner(rpc_wasm, wallet, {
gasPrice: GasPrice.fromString(answers.gasPrice ? answers.gasPrice + "usei" : "0.1usei")
})
let collectionConfig = await client.queryContractSmart(lighthouse, { get_collection: { collection } })
let group: any = null
for (let g of collectionConfig.mint_groups) {
if (g.name === groupName) {
group = g
break;
}
}
if (group === null) {
console.log(chalk.red("Group not found"))
return
}
let merkleProof: any = null
let hashedAddress: any = null
if (group.merkle_root !== "" && group.merkle_root !== null) {
//ask for proof
let proof = await inquirer.prompt([
{
type: "input",
name: "proof",
message: "Enter Merkle proof for group " + groupName + " separated by commas"
}
])
let proofArray = proof.proof.split(",")
merkleProof = proofArray.map((p: string) => Array.from(Buffer.from(p, 'hex')))
}
let spinner = ora("Minting NFT").start()
const mintMsg = {
mint: {
collection,
group: groupName,
merkle_proof: merkleProof,
amount: amount
}
}
interface Coin {
denom: string;
amount: string;
}
let mintReceipt = await client.execute(firstAccount.address, lighthouse, mintMsg, "auto", "", []);
spinner.succeed("NFT minted")
console.log("Transaction hash: " + chalk.green(mintReceipt.transactionHash))
const events = mintReceipt.logs[0].events
let tokenIds;
// Find the event with the type 'wasm'
for (const event of events) {
if (event.type === 'wasm') {
// Find the attribute with the key 'collection'
for (const attribute of event.attributes) {
if (attribute.key === 'token_ids') {
tokenIds = attribute.value;
}
}
}
}
console.log("Token IDs: " + chalk.green(tokenIds))
})
}