Lowdb return undefined - javascript

I'm doing a Discord bot with command handling, but on a file, I can't get the content of my JSON file out with lowdb... I proceed exactly the same way with success in the other files, I don't understand... Here is my code:
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('../db.json')
const db = low(adapter)
const adapter2 = new FileSync('../users.json')
const users = low(adapter2)
const fetch = require('node-fetch');
const config = require('../config.json');
const api = config.api;
module.exports = {
name: 'rent',
description: 'Rent a number',
usage: '<country>',
guildOnly: true,
async execute(message, args) {
return console.log(db.get().value())
...
Here's my db.json:
{
"numbers": [
{
"test": "1234"
}
]
}
When I console.log db alone, it takes me out the object, but as soon as I try to console.log with lowdb like above it takes me out undefined ....

So I'm not sure why, but you have to remove a point on the road to lowdb files.
Code not working:
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('../db.json')
const db = low(adapter)
const adapter2 = new FileSync('../users.json')
const users = low(adapter2)
const fetch = require('node-fetch');
const config = require('../config.json');
const api = config.api;
Code after modification and functional:
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('./db.json')
const db = low(adapter)
const adapter2 = new FileSync('./users.json')
const users = low(adapter2)
const fetch = require('node-fetch');
const config = require('../config.json');
const api = config.api;

Related

Binance API-key Trading Bot - InvalidNonce: binance {"code":-1021,"msg":"Timestamp for this request is outside of the recvWindow."}

I have re-created a Binance API-key trading bot which uses NodeJS, CCXT & Axios (It pulls the API+secret key from a .env file). I am getting the error when trying to execute the trading-bot;;
PS C:\Users\mwalk\Documents\Crypto-Bot> node index.js
C:\Users\mwalk\Documents\Crypto-Bot\node_modules\ccxt\js\base\Exchange.js:640
throw new exact[string] (message)
^
InvalidNonce: binance {"code":-1021,"msg":"Timestamp for this request
is outside of the recvWindow."}
at binance.throwExactlyMatchedException (C:\Users\mwalk\Documents\Crypto-Bot\node_modules\ccxt\js\base\Exchange.js:640:19)
require('dotenv').config();
const ccxt = require('ccxt');
const axios = require('axios');
const tick = async(config, binanceClient) => {
const { asset, base, spread, allocation } = config
const market = `${asset}/${base}`;
const orders = await binanceClient.fetchOpenOrders(market);
orders.forEach(async order => {
await binanceClient.cancelOrder(order.id);
});
const results = await Promise.all([
axios.get('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd'),
axios.get('https://api.coingecko.com/api/v3/simple/price?ids=tether&vs_currencies=usd')
]);
const marketPrice = results [0].data.bitcoin.usd / results[1].data.tether.usd;
const sellPrice = marketPrice * (1 + spread);
const buyPrice = marketPrice * (1 - spread);
const balances = await binanceClient.fetchBalance();
const assetBalance = balances.free[asset];
const baseBalance = balances.free[base];
const sellVolume = assetBalance * allocation;
const buyVolume = (baseBalance * allocation) / marketPrice;
await binanceClient.createLimitSellOrder(market, sellVolume, sellPrice);
await binanceClient.createLimitBuyOrder(market, buyVolume, buyPrice);
console.log(`
New tick for ${market}...
Created limit sell order for ${sellVolume}#${sellPrice}
Create limit buy order for ${buyVolume}#${buyPrice}
`);
}
const run = () => {
const config = {
asset: 'BTC',
base: 'USDT',
allocation: 0.1,
spread: 0.1,
tickInterval: 2000
};
const binanceClient = new ccxt.binance({
apiKey: process.env.API_ENV,
secret: process.env.API_SECRET
});
tick(config, binanceClient);
setInterval(tick, config.tickInterval, config, binanceClient);
};
run();
sync your pc time with nist option from your control panel

How to complete swap method for JustSwap smart-contract

I'am trying to complete JustSwap-contract S-USDT-TRX Token (TQn9Y2khEsLJW1ChVWFMSMeRDow5KcbLSE)
But I am getting a response in the console:
REVERT opcode executed
My code:
const TronWeb = require("tronweb");
const ethers = require("ethers")
const MAINNET_RPC = "https://api.trongrid.io";
const PLACEHOLDER_PRIVATE_KEY = "YOUR_PRIVATE_KEY";
const HttpProvider = TronWeb.providers.HttpProvider;
const fullNode = new HttpProvider(MAINNET_RPC);
const solidityNode = new HttpProvider(MAINNET_RPC);
const eventServer = new HttpProvider(MAINNET_RPC);
const tronWeb = new TronWeb(fullNode,solidityNode,eventServer,PLACEHOLDER_PRIVATE_KEY);
const startJustSwap = async () => {
try {
const contractTokenExchangeUSDT = 'TQn9Y2khEsLJW1ChVWFMSMeRDow5KcbLSE'; //S-USDT-TRX Token
const parameters = [{type: `uint256`, value: 10000000},{type: `uint256`,value: 1614346581000}];
const tx = await tronWeb.transactionBuilder.triggerConstantContract(contractTokenExchangeUSDT, `trxToTokenSwapInput(uint256,uint256)`, {},parameters)
console.log(tx);
} catch (e) {
console.log(e);
}
};
startJustSwap();
I have very good result when I detected price. For example:
const tx = await tronWebLocal.transactionBuilder.triggerConstantContract(contractToken, `getTokenToTrxOutputPrice(uint256)`, {},
[{
type: `uint256`,
value: 10000000,
}])
But I can't swap. I am using a connection like this and get error "REVERT opcode executed":
const tx = await tronWebLocal.transactionBuilder.triggerConstantContract(contractToken, `trxToTokenSwapInput(uint256,uint256)`, {}, [{ type: `uint256`, value: },{ type: `uint256`, value: 10}]);
Could you help me make the correct code?
Thank you very much!
triggerConstantContract is to Trigger the constant of the smart contract and the transaction is off the blockchain. You can only read the contract by this.(Say price in your case).
Try this : https://developers.tron.network/reference#triggersmartcontract
Format: tronWeb.transactionBuilder.triggerSmartContract(contractAddress,functions, options,parameter,issuerAddress);

interacting with ganache-cli fork through script

const {ChainId, Fetcher, WETH, Route, Trade, TokenAmount, TradeType, Percent} = require ('#uniswap/sdk');
const ethers = require('ethers');
const chainId = ChainId.MAINNET;
how would I specify it to be the locally forked ganache chain?
tried this:
const Web3 = require('web3');
const web3 = new Web3(`http://localhost:8545`);
const tokenAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F';
const init = async ()=> {
const chainId = await web3.eth.getChainId();
...
following error is shown:
/Users/GreyShadow/node_modules/#ethersproject/logger/lib/index.js:179
var error = new Error(message);
^
Error: unsupported getDefaultProvider network (operation="getDefaultProvider", network={"chainId":1337,"name":"unknown"}, code=NETWORK_ERROR, version=providers/5.0.17)
Help is much appreciated

Changes of a json not taken into account NodeJS

I'm coming to you because I'm trying to do a foreach loop on Discord.JS to detect changes in a JSON file. My file does change content, but my foreach loop keeps the old content in memory. I have no idea how to solve the problem...
My index.js:
const Discord = require('discord.js');
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const fetch = require('node-fetch');
const client = new Discord.Client();
const config = require('./config.json');
const database = require('./db.json');
const adapter = new FileSync('./db.json')
const db = low(adapter)
const prefix = config.prefix;
let api = config.api;
client.once('ready', () => {
db.defaults({numbers: []})
.write()
setInterval(function() {
database.numbers.forEach(async element => {
let state = await fetch(`some-api-url`).then(response => response.json());
if(state[0].response != element.response){
db.get('numbers')
.find({number: element.number})
.assign({response: state[0].response, sms: state[0].msg})
.write();
let user = element.clientId;
try {
await client.users.cache.get(user).send(`Your message for number ${element.number} is ${element.sms}`);
} catch(error){
console.log(error)
}
}
});
}, 3000);
console.log('Ready!');
});
It all works, it just keeps the old file in memory.
To solve this problem, I passed my const database = require('./db.json'); into let. Then I integrated fs so that I could clear the cache:
setInterval(function() {
delete require.cache[require.resolve('./db.json')]
database = require('./db.json');
Problem solved!

How do I send transactions and transfer TT on ThunderCore mainnet?

Without using ThunderCore Hub or any Web3 wallet which supports Thunder Token, how could I programmatically send transactions or transfer Thunder Tokens?
To send a transaction on Thundercore, set these fields in the transaction:
set chainId with from net_version() (eth.net.getId())
set nonce with the value of eth_getTransactionCount() (eth.getTransactionCount)
set gas price from eth_gasPrice() (getGasPrice)
set gas limit from eth_estimateGas (eth.estimateGas)
See the submitTx method in the following code:
transfer.js
const fs = require('fs');
const path = require('path');
const Accounts = require('web3-eth-accounts');
const Eth = require('web3-eth');
const Web3 = require('web3');
const BN = Web3.utils.BN;
const pretty = require('./pretty');
const erc20Abi = require('./ERC20.abi.json');
const web3Provider = () => {
return Eth.giveProvider || 'https://mainnet-rpc.thundercore.com';
}
const signTx = async (fromAccount, tx) => {
const signedTx = await fromAccount.signTransaction(tx)
return signedTx.rawTransaction // hex string
}
class ChainHelper {
constructor(eth, chainId, fromAccount) {
this.eth = eth;
this.chainId = chainId;
this.fromAccount = fromAccount;
this.fromAddress = fromAccount.address;
}
async submitTx(toAddress, value, txData) {
const eth = this.eth;
const promiseResults = await Promise.all([
eth.getTransactionCount(this.fromAccount.address),
eth.getGasPrice(),
]);
const nonce = promiseResults[0];
const gasPrice = promiseResults[1];
const fromAddress = this.fromAddress;
const tx = {
'gasLimit': 0,
'chainId': this.chainId,
'gasPrice': gasPrice,
'nonce': nonce,
'from': fromAddress,
'to': toAddress,
'value': value,
'data': txData,
}
const gasMultiple = new BN(1.0);
tx.gasLimit = '0x' + (new BN(await eth.estimateGas(tx))).mul(gasMultiple).toString(16);
console.log('tx:', pretty.format(tx));
const rawTxStr = await signTx(this.fromAccount, tx);
return eth.sendSignedTransaction(rawTxStr);
}
async transferToken (contractAddress, toAddress, value) {
const eth = this.eth;
const contractAbi = erc20Abi;
const contract = new eth.Contract(contractAbi, contractAddress);
const txData = contract.methods.transfer(toAddress, value).encodeABI();
return this.submitTx(contractAddress, 0, txData);
}
}
const create = async (privateKey) => {
const accounts = new Accounts();
if (!privateKey.startsWith('0x')) {
privateKey = '0x' + privateKey;
}
const account = accounts.privateKeyToAccount(privateKey);
const eth = new Eth(web3Provider());
const networkId = await eth.net.getId();
return new ChainHelper(eth, networkId, account);
}
const readKeys = () => {
const privateKeys = fs.readFileSync(path.join(__dirname, '..', '.private-keys'),
{encoding: 'ascii'}).split('\n').filter(x => x.length > 0);
return privateKeys;
}
module.exports = {
create: create,
readKeys: readKeys,
};
testTransfer.js
const fs = require('fs');
const path = require('path');
const ChainHelper = require('../src/transfer.js');
const toAddress = '0x6f0d809e0fa6650460324f26df239bde6c004ecf';
describe('transfer', () => {
it('transfer TT', async() => {
const privateKey = ChainHelper.readKeys()[0]
const c = await ChainHelper.create(privateKey);
c.submitTx(toAddress, 1, '');
});
it('tokenTransfer', async() => {
const privateKey = ChainHelper.readKeys()[0]
const c = await ChainHelper.create(privateKey);
/* Token.issue() */
const jsonBuf = fs.readFileSync(path.join(__dirname, '..', 'build', 'contracts', 'Token.json'));
const contractData = JSON.parse(jsonBuf);
const contractAbi = contractData['abi'];
const contractAddress = contractData['networks'][c.chainId]['address'];
const contract = new c.eth.Contract(contractAbi, contractAddress);
const toAddress = c.fromAddress;
const tokenAmount = 2;
let txData = contract.methods.issue(tokenAmount, c.fromAddress).encodeABI();
let r = await c.submitTx(toAddress, 0, txData);
console.log('Token.issue receipt:', r);
/* Token.transfer() */
r = await c.transferToken(contractAddress, toAddress, tokenAmount)
console.log('Token.transfer receipt:', r);
});
});
The code above targets the command line or server-side node.js, to send transactions from a browser replace signTx and eth.sendSignedTransaction with web3.eth.sendTransaction
The complete example is in the transfer branch of this field-support repo.

Categories