I am trying to update via API some of my arts on a NFT test over OpenSea, now he updates but the problem is that he is repeating the numbers, is it possible to choose a number in a range but that never repeat?
My actual code:
const opensea = require("opensea-js");
const OpenSeaPort = opensea.OpenSeaPort;
const Network = opensea.Network;
const MnemonicWalletSubprovider = require("#0x/subproviders")
.MnemonicWalletSubprovider;
const RPCSubprovider = require("web3-provider-engine/subproviders/rpc");
const Web3ProviderEngine = require("web3-provider-engine");
const MNEMONIC = 'SECRET';
const NODE_API_KEY = 'MyKEY';
const isInfura = true;
const FACTORY_CONTRACT_ADDRESS = '0x745e6b0CAd1eDc72647B9fFec5C69e4608f73ab2';
const NFT_CONTRACT_ADDRESS = '0x745e6b0CAd1eDc72647B9fFec5C69e4608f73ab2';
const OWNER_ADDRESS = '0xaEBB892210eB23C47b1e710561c7BC4CFA63A62e';
const NETWORK = 'rinkeby';
const API_KEY = ""; // API key is optional but useful if you're doing a high volume of requests.
if (!MNEMONIC || !NODE_API_KEY || !NETWORK || !OWNER_ADDRESS) {
console.error(
"Please set a mnemonic, Alchemy/Infura key, owner, network, API key, nft contract, and factory contract address."
);
return;
}
if (!FACTORY_CONTRACT_ADDRESS && !NFT_CONTRACT_ADDRESS) {
console.error("Please either set a factory or NFT contract address.");
return;
}
const BASE_DERIVATION_PATH = `44'/60'/0'/0`;
const mnemonicWalletSubprovider = new MnemonicWalletSubprovider({
mnemonic: MNEMONIC,
baseDerivationPath: BASE_DERIVATION_PATH,
});
const network =
NETWORK === "mainnet" || NETWORK === "live" ? "mainnet" : "rinkeby";
const infuraRpcSubprovider = new RPCSubprovider({
rpcUrl: isInfura
? "https://" + network + ".infura.io/v3/" + NODE_API_KEY
: "https://eth-" + network + ".alchemyapi.io/v2/" + NODE_API_KEY,
});
const providerEngine = new Web3ProviderEngine();
providerEngine.addProvider(mnemonicWalletSubprovider);
providerEngine.addProvider(infuraRpcSubprovider);
providerEngine.start();
const seaport = new OpenSeaPort(
providerEngine,
{
networkName:
NETWORK === "mainnet" || NETWORK === "live"
? Network.Main
: Network.Rinkeby,
apiKey: API_KEY,
},
(arg) => console.log(arg)
);
async function sellTheItems() {
// Example: simple fixed-price sale of an item owned by a user.
console.log("Auctioning an item for a fixed price...");
//Get a number in a range and return as a string
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
const fixedPriceSellOrder = await seaport.createSellOrder({
asset: {
tokenId: getRandomInt(0, 500).toString(),
//tokenId: "0",
tokenAddress: NFT_CONTRACT_ADDRESS,
},
startAmount: 0.36,
expirationTime: 0,
accountAddress: OWNER_ADDRESS,
});
console.log(
`Successfully created a fixed-price sell order! ${fixedPriceSellOrder.asset.openseaLink}\n`
);
}
async function doItAgain() {
sellTheItems();
}
//Repeat doItAgain() every 5 seconds
setInterval(doItAgain, 5000);
What I want to do is get a number between 0 and 500 but never repeat a number that I used before, my intention is get a number to 'tokenId' everytime.
With respect, it's a bad idea to use 3-digit "random" tokens. Partly because you get duplicates and you need some sort of storage to avoid that. Partly because they're easy to brute-force.
Use the uuid Universal Unique IDentifier package to generate 128-bit uuidv4 tokens of which 60 bits are random, using a crypographically secure pseudo-random number generator. All uuids, not just the uuidv4 random ones, are constructed to avoid duplicates. But the uuidv4 tokens have the advantage that they're very hard for cybercreeps to guess.
const { v4: uuidv4 } = require('uuid');
...
tokenId: uuidv4(), // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
Related
function ChangePts(pts) {
this.pts = pts;
this.win = function() {
console.log(this.pts + 30)
return this.pts += 30
}
this.lose = function() {
console.log(this.pts - 30)
return this.pts -= 30;
}
};
I made it to calculate how many games you need to lose, to get certain ratingw with while loop. This implies that win% is 0%, how do I calculate amount of games if we declare starting pts for example 5000, how many games it takes to get to 1000 pts if your winrate is 27%
P.S.: For this case I need only negative amount of win%.
You can just calculate it like this (variables should be explanation enough). There is no real coding necessary for it, just math calculations
const winRate = 0.27
const loseRate = 1-winRate
const pointsWin = 30
const pointsLose = 30
const startingPoints = 5000
const targetPoints = 1000
const pointsGainedOnAverage = pointsWin*winRate - pointsLose*loseRate
const pointsDistance = targetPoints - startingPoints
const games = pointsDistance / pointsGainedOnAverage
console.log('games', games)
I'm trying to make a simple daily follower stats like the screenshot below.
And here's the code I'm using.
const normalize = ({ min, max, number }) => {
return parseFloat((((number - min) / (max - min)) * 100).toFixed(2))
}
const followers = {
'03-23-2022': 2115,
'03-24-2022': 2128,
'03-25-2022': 2175,
'03-26-2022': 2195,
'03-27-2022': 2215,
'03-28-2022': 2206,
'03-29-2022': 2258
}
const numbers = []
for (const day in followers) {
const stats = followers[day]
numbers.push(stats)
}
const min = Math.min.apply(null, numbers)
const max = Math.max.apply(null, numbers)
for (const day in followers) {
const activity = followers[day]
const percent = normalize({ min, max, number: activity })
console.log({ day, activity, percent })
}
As you can see on the console log the normalize function returns 0 for the minimum number and that's why nothing is visible on the site.
What I'd like to do is I want to get some meaningful numbers from the normalize function to be able to show the stats in a more readable style. How do I do that?
I'm currently making a Discord bot using JavaScript, the bot features many commands, but I just came across this flaw, the flaw concerns the Math.Random() object, except it sometimes returns negative numbers, does anyone have a solution to this using one of the methods?
Here's the code::
let db = require(`quick.db`)
module.exports = {
name: "rob",
description: "Rob your friends to get money",
category: "economy",
usage: "rob [member]",
timeout: "1 minute",
run: async (client, message, args) => {
let victim = message.mentions.members.first()
if(!victim) {
return message.channel.send(`:x: Please specify a member to rob!`)
}
let victimW = await db.get(`wallet_${victim.id}`)
if(victimW === null) {
message.channel.send(`:x: That user doesn't have money in his wallet, are you sure you want to rob him?`)
}
let random = Math.floor(Math.random() * 100);
if(random < 30) {
let victimWallet = await db.get(`wallet_${victim.id}`)
let userWallet = await db.get(`wallet_${message.author.id}`)
let amount = Math.floor(Math.random() * victimWallet);
const messages = [`POG! You robbed **${victim.username}** and got **${amount}** :coin:!`, `oo seems like you robbed **${victim.displayName}** and got **${amount}** :coin:!`]
const randomMessage = messages[Math.floor(Math.random() * messages.length)];
message.channel.send(randomMessage)
await db.set(`wallet_${victim.id}`, amount - victimWallet)
await db.set(`wallet_${message.author.id}`, userWallet + amount)
} else if(random > 30) {
let authorWallet = await db.get(`wallet_${message.author.id}`)
let wallet1 = await db.get(`wallet_${victim.id}`)
let amountPaid = Math.floor(Math.random() * authorWallet);
const message1 = [`Pfft noob, you got caught and paid **${victim.displayName} ${amountPaid}** :coin: lol!`, `lel ure such a noob, you paid **${victim.displayName} ${amountPaid}** :coin:!`, `u suck and you paid **${amountPaid}** :coin: to **${victim.displayName}**, such a noob lol!`]
const randomMessage1 = message1[Math.floor(Math.random() * message1.length)];
return message.channel.send(randomMessage1)
await db.set(`wallet_${message.author.id}`, (amountPaid - authorWallet));
await db.set(`wallet_${message.author.id}`, (amountPaid + wallet1));
}
}
}
It all works except sometimes it just sends a negative number, can anyone tell me a math method that make sure the number isn't a negative?
Thanks.
You should verify the amount to steal before stealing it
if (random < 30) {
let victimWallet = await db.get(`wallet_${victim.id}`)
let userWallet = await db.get(`wallet_${message.author.id}`)
let amount = Math.floor(Math.random() * victimWallet);
//Check the amount of victim wallet, return if not enough coins to steal
if (amount > victimwallet) {
console.log("Not enough coins to steal") return;
}
const messages = [`POG! You robbed **${victim.username}** and got **${amount}** :coin:!`, `oo seems like you robbed **${victim.displayName}** and got **${amount}** :coin:!`]
const randomMessage = messages[Math.floor(Math.random() * messages.length)];
message.channel.send(randomMessage)
await db.set(`wallet_${victim.id}`, amount - victimWallet)
await db.set(`wallet_${message.author.id}`, userWallet + amount)
}
If the point is just to make the output to always positive, you can try this "if condition"
var x = -10 //change it with any number
if (x < 0){
x = x * -1
}
console.log(x) //it should will always show positive number
alternatively you can always use Match.abs(x)
var x = -10;
console.log(Math.abs(x));
I'm currently programming a Discord bot, and was wondering if it is possible to predict the wanted command if the input was incorrect.
For example, I have this list of words :
['help','meme','ping'],
and if the user inputs "hepl", would it somehow be possible to "guess" they meant to type help ?
One option would be to find a command whose levenshtein distance from the input is 2 or less:
// https://gist.github.com/andrei-m/982927
const getEditDistance=function(t,n){if(0==t.length)return n.length;if(0==n.length)return t.length;var e,h,r=[];for(e=0;e<=n.length;e++)r[e]=[e];for(h=0;h<=t.length;h++)r[0][h]=h;for(e=1;e<=n.length;e++)for(h=1;h<=t.length;h++)n.charAt(e-1)==t.charAt(h-1)?r[e][h]=r[e-1][h-1]:r[e][h]=Math.min(r[e-1][h-1]+1,Math.min(r[e][h-1]+1,r[e-1][h]+1));return r[n.length][t.length]};
const commands = ['help','meme','ping'];
const getCommand = (input) => {
if (commands.includes(input)) return input;
return commands.find(command => getEditDistance(input, command) <= 2);
};
console.log(getCommand('hepl'));
(2 is just a number, feel free to pick the tolerance you want - the higher it is, the more commands will be guessed at, but the more false positives there will be)
You can find hits and show many words in suggestion. If you want same you can use to show most hit word.
const words = ["help", "meme", "ping"];
const getHits = (word, wordToMatch, hits = 0) => {
if (!word.length || !wordToMatch.length) return hits;
let charW = word.slice(0, 1);
let index = wordToMatch.indexOf(charW);
if (index !== -1) {
return getHits(
word.slice(1),
String(wordToMatch.slice(0, index) + wordToMatch.substr(index + 1)),
hits + 1
);
}
return getHits(word.slice(1), wordToMatch, hits);
};
const getMatch = mword => {
return words.reduce((m, word) => {
m[word] = getHits(mword, word);
return m;
}, {});
};
const sort = obj => {
return Object.entries(obj).sort(
([_, value1], [__, value2]) => value2 - value1
);
};
console.log(getMatch("help"));
console.log(sort(getMatch("help")));
console.log(getMatch("me"));
console.log(sort(getMatch("me")));
.as-console-row {color: blue!important}
My 'problem' is more of a feature I am looking to add, I used this guide:
https://anidiots.guide/coding-guides/sqlite-based-points-system
I changed the code a little to mainly give you a random amount of XP, I am looking to edit how much XP is needed to level up.
Right now it is a static amount, being 5000 needed to level up. I am trying to make it increase the amount needed to level up by an extra 5000 each time you level up.
Currently, it works like this:
Level 1 to 2 = 5000 total XP needed
Level 2 to 3 = 10000 total xp needed
Currently, the amount needed to level up is always 5000 between each level.
This is how I want it to work:
Level 1 to 2 = 5000 total XP needed
Level 2 to 3 = 15000 total XP needed
Which will be 5000 to level 2 and then 10000 to level 3 and so on (increasing the amount needed by 5000 each time you level up)
I spent the best part of 2 hours trying different things, and mainly looking at the code being completely out of my depth.
I believed that doing something like this would work, but I have no idea if it's correct
if (score.level == '1') {
nextLevel = 5000
}
if (score.level == '2' {
nextLevel = 10000
}
I highly doubt this is correct, otherwise, my message event would be very long, as I plan to have 100 levels
The code in its entirety:
let score;
if (message.guild) {
score = bot.getScore.get(message.author.id, message.guild.id);
if (!score) {
score = {
id: `${message.guild.id}-${message.author.id}`,
user: message.author.id,
guild: message.guild.id,
points: 0,
level: 1,
};
}
const xpAdd = Math.floor(Math.random() * 10) + 50;
const curxp = score.points;
const curlvl = score.level;
const nxtLvl = score.level * 5000;
score.points = curxp + xpAdd;
if (nxtLvl <= score.points) {
score.level = curlvl + 1;
const lvlup = new MessageEmbed()
.setAuthor(
`Congrats ${message.author.username}`,
message.author.displayAvatarURL()
)
.setTitle('You have leveled up!')
.setThumbnail('https://i.imgur.com/lXeBiMs.png')
.setColor(color)
.addField('New Level', curlvl + 1);
message.channel.send(lvlup).then(msg => {
msg.delete({
timeout: 10000,
});
});
}
bot.setScore.run(score);
}
The code as-is works fine and as expected, but as-is is not very good, as there is no reward from going from level 30-31 as it's the same amount of XP needed to get from level 1-2
Here's a little formula which should do the trick (if I understand your problem correctly):
const nxtLvl = 5000 * (Math.pow(2, score.level) - 1);
This gives the following xp requirements to level up:
1->2: 5000
2->3: 15000
3->4: 35000
4->5: 75000
5->6: 155000
Try something like this:
const levels = [0, 5000, 15000, 30000, 50000, 75000];
....
nextLevel = levels[score.level];
Edit
#Dan you mean like this:
nextLevel = 5000 * Math.round( score.level * (score.level + 1) / 2 );
Here Is Code I'm Using
But Problem Is I Can't Add Or Remove XP
Also I Made It With Scratch So I'm Being Mad Understanding This
let Discord;
let Database;
if (typeof window !== "undefined") {
Discord = DiscordJS;
Database = EasyDatabase;
} else {
Discord = require("discord.js");
Database = require("easy-json-database");
}
const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(), ms));
const s4d = {
Discord,
client: null,
tokenInvalid: false,
reply: null,
joiningMember: null,
database: new Database("./db.json"),
checkMessageExists() {
if (!s4d.client) throw new Error('You cannot perform message operations without a Discord.js client')
if (!s4d.client.readyTimestamp) throw new Error('You cannot perform message operations while the bot is not connected to the Discord API')
}
};
s4d.client = new s4d.Discord.Client({
fetchAllMembers: true
});
s4d.client.on('raw', async (packet) => {
if (['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)) {
const guild = s4d.client.guilds.cache.get(packet.d.guild_id);
if (!guild) return;
const member = guild.members.cache.get(packet.d.user_id) || guild.members.fetch(d.user_id).catch(() => {});
if (!member) return;
const channel = s4d.client.channels.cache.get(packet.d.channel_id);
if (!channel) return;
const message = channel.messages.cache.get(packet.d.message_id) || await channel.messages.fetch(packet.d.message_id).catch(() => {});
if (!message) return;
s4d.client.emit(packet.t, guild, channel, message, member, packet.d.emoji.name);
}
});
var member_xp, member_level;
s4d.client.login('My Dumb Token').catch((e) => {
s4d.tokenInvalid = true;
s4d.tokenError = e;
});
s4d.client.on('message', async (s4dmessage) => {
if (!((s4dmessage.member).user.bot)) {
member_xp = s4d.database.get(String(('xp-' + String(s4dmessage.author.id))));
member_level = s4d.database.get(String(('level-' + String(s4dmessage.author.id))));
if (!member_xp) {
member_xp = 0;
} else if (!member_level) {
member_level = 0;
}
s4d.database.set(String(('xp-' + String(s4dmessage.author.id))), (member_xp + 1));
member_xp = member_xp + 1;
if (member_xp > 100) {
s4d.database.set(String(('level-' + String(s4dmessage.author.id))), (member_level + 1));
member_level = member_level + 1;
s4dmessage.channel.send(String((['Congratulations, ', s4dmessage.member, 'you jumped to level ', member_level, '!!'].join(''))));
}
if ((s4dmessage.content) == '-level') {
s4dmessage.channel.send(String(([s4dmessage.member, ', you are currently level: ', member_level].join(''))));
} else if ((s4dmessage.content) == '-xp') {
s4dmessage.channel.send(String(([s4dmessage.member, ', you need ', 100 - member_xp, ' to jump to level ', member_level + 1].join(''))));
}
}
});
s4d;