tronWeb getAccount returns null - node.js

(async function () {
const TronWeb = require('tronweb');
const HttpProvider = TronWeb.providers.HttpProvider;
const fullNode = new HttpProvider('https://api.trongrid.io');
const solidityNode = new HttpProvider('https://api.trongrid.io');
const eventServer = 'https://api.trongrid.io/';
const privateKey = "04EE63599802B5D31A29C95CC7DF04F427E8F0A124BED9333F3A80404ACFC3127659C540D0162DEDB81AC5F74B2DEB4962656EFE112B252E54AC3BA1207CD1FB1004EE63599802B5D31A29C95CC7DF04F427E8F0A124BED9333F3A80404ACFC3127659C540D0162DEDB81AC5F74B2DEB4962656EFE112B252E54AC3BA1207CD1FB10";
const apiKey ='92959baa-2df2-4292-8309-d87ef88a56d6';
const tronWeb = new TronWeb(fullNode, solidityNode, eventServer, privateKey)
tronWeb.setHeader({"TRON-PRO-API-KEY": '92959baa-xxx-4292-xxx-d87xxa56d6'});
const newAccount = await tronWeb.createAccount();
//return {
privateKey: 'xxxxxxxxx',
publicKey: 'xxxxxxxxxx',
address: {
base58: 'TURYhSKCw3m84MaKmYhoYqd72ULHRn5zJy',
hex: '41CA6D8549A64DA49324248140789B5A4F52EB022B'
}
}
const account = await tronWeb.trx.getAccount('TURYhSKCw3m84MaKmYhoYqd72ULHRn5zJy');
console.log(account) // returns null object {}
})()
if i try tronWeb.trx.getAccount function it returns null, i asked CHATGPT it said possible this wallet hasnt any transaction that why it returns null,
but i deposited 5 usdt to "TX5pWLD2LbaUaF56L4w7Pqwtg2Wp7eKDZ3" this wallet created by tronWeb.createAccount() when i try request i am getting same action.
uys what is the problem any body can solve this?
i am trying create some wallets TRC20 USDT deposit,transactions etc..
(i used tronweb#4.4 and tronweb#3.2 given same null object result)

Related

DiscordAPIError[50035]: Invalid Form Body data.content[BASE_TYPE_MAX_LENGTH]: Must be 2000 or fewer in length

I Have the Data I Pulled from the Internet via Node js in My Bot
I wanted to share, but I get max_lenght error because the text is too long, what should I do?
the code i wrote;
const interactionCreate = require("../events/interactionCreate");
const Parser = require('rss-parser');
const { SlashCommandBuilder } = require("discord.js");
const parser = new Parser()
const { Routes } = require('discord-api-types/v9')
const { request } = require('undici')
const { EmbedBuilder } = require('discord.js');
const fs = require("fs")
const jsonToTxt = require("json-to-txt");
module.exports = {
name: "adsoyad",
description: "ad soyad bilgi ",
options:[
{
name: "adı",
description: "sorgulanacak kişi ismi",
type: 3,
required: true,
},
{
name: "soyadı",
description : "sorgulanacak kişi soyadı",
type: 3,
required: true,
}
],
run: async (client, interaction) =>{
//const ad = interaction.options.getString("ad");
// const soyad = interaction.options.getString("soyad");
//const feed = await parser.parseURL(`[URL]http://141.11.127.168/ucretsizapi/adsoyad.php?ad=&soyad=sezer&auth=propenthia[/URL]`)
const ad = interaction.options.getString('adı');
const soyad = interaction.options.getString('soyadı');
const query = new URLSearchParams({ ad });
const query2 = new URLSearchParams({ soyad });
const dictResult = await request(`http://141.11.127.168/ucretsizapi/adsoyad.php?${query}&${query2}&auth=propenthia`);
//const list = await dictResult.body.text();
const asa = await dictResult.body.text(8000);
//fs.writeFileSync("data.json", JSON.stringify(asa));
// Convert the JSON data to a text file
//jsonToTxt("data.json", "data.txt");
interaction.length = 8000
//fs.writeFileSync(asa)
await interaction.reply(`${asa}`)
//const ms = await JSON.stringify(list)
//var mars = JSON.parse(ms)
}
}
the error i got;
throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
^
DiscordAPIError\[50035\]: Invalid Form Body
data.content\[BASE_TYPE_MAX_LENGTH\]: Must be 2000 or fewer in length.
at SequentialHandler.runRequest (C:\\Users\\trwor\\OneDrive\\Masaüstü\\%64 bot Project\\node_modules\\#discordjs\\rest\\dist\\index.js:667:15)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async SequentialHandler.queueRequest (C:\\Users\\trwor\\OneDrive\\Masaüstü\\%64 bot Project\\node_modules\\#discordjs\\rest\\dist\\index.js:464:14)
at async REST.request (C:\\Users\\trwor\\OneDrive\\Masaüstü\\%64 bot Project\\node_modules\\#discordjs\\rest\\dist\\index.js:910:22)
at async ChatInputCommandInteraction.reply (C:\\Users\\trwor\\OneDrive\\Masaüstü\\%64 bot Project\\node_modules\\discord.js\\src\\structures\\interfaces\\InteractionResponses.js:111:5)
at async Object.run (C:\\Users\\trwor\\OneDrive\\Masaüstü\\%64 bot Project\\commands\\adsoyad.js:64:9) {
requestBody: {
I need your help my friends, thank you in advance to those who try to solve it, frankly, I had a very difficult time.

API Request passing ID fetched from mongodb

I´m a Java Dev so I need help from NodeJS guys!
Task: create a script that retrieves '_id', 'document', and 'corporateName' from MongoDB, then take the retrieved '_id', and pass it as a parameter to an API request. The last part should be taking 'document', 'corporateName' + 'client_id', 'client_secret' and export it into a single csv file.
It might be a very simple script! Therefore I´ve done this till now:
const {MongoClient} = require('mongodb');
const uri = "mongodb+srv://<privateInfo>/";
const client = new MongoClient(uri);
async function run() {
try {
const database = client.db("merchant-profile");
const ecs = database.collection("merchant_wallet");
const api = `https://<prodAPI>/v1/merchant/wallet/${id}/oauth2`;
const ecOpt = {_id: 1, document: 1, corporateName: 1};
const credOpt = {client_id: 1, client_secret: 1};
const ec = ecs.find({}).project(ecOpt);
let id = ec.forEach(id => cred._id);
const cred = api.find({}).project(credOpt);
await cred.forEach(console.dir);
} finally {
await client.close();
}
}
run().catch(console.dir);
I´m trying to understand how can I take '_id' fetched in 'ec' and pass it as a param to the 'cred' call.
This would already be awesome!
If you could help me out with the CSV issue as well it would be perfect.
So I don´t want just the answer, but understand how to do this.
Thank you all in advance!
This is the way I found to do it:
const { default: axios } = require("axios");
const { MongoClient } = require("mongodb");
const uri = "mongodb+srv://admin:sLKJdsdRp4LrsVtLsnkR#pp-core-prd.fy3aq.mongodb.net/";
const client = new MongoClient(uri);
async function run() {
try {
const database = client.db("merchant-profile");
const ecs = database.collection("merchant_wallet");
const data = [];
await ecs.find({}).forEach(async function teste(response) {
const id = response._id;
const api = `https://api.pedepronto.com.br/v1/merchant/wallet/${id}/oauth2`;
try{
const res = await axios.get(api);
data.push({client_secret: res.data[0].client_secret, client_id: res.data[0].client_id})
}catch(e){
console.log(e);
}
})
} finally {
await client.close();
}
}
run().catch(console.dir);
It iterates over the find method and appends the fetched id to the uri.

Uniswap V3 AlphaRouter - "Failed to get subgraph pools from any providers"

I am trying to swap WETH against MyToken from a previously created Uniswap V3 pool on Arbitrum Rinkeby. When calling AlphaRouter.route, however, I get the following error message
Failed to get subgraph pools from any providers
What is still missing to swap?
What do I need to create?
My target is to swap WETH for a given output of MyToken.
I am trying to simply get a swap on Uniswap V3 with my pool done. Any ideas?
const Web3 = require('web3');
const {
ethers
} = require("ethers");
const HDWalletProvider = require('#truffle/hdwallet-provider');
const {
Token,
CurrencyAmount,
TradeType,
Percent
} = require("#uniswap/sdk-core");
const {
AlphaRouter
} = require('#uniswap/smart-order-router');
const ABI_UNISWAP_POOL_V3 = require("#uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Pool.sol/IUniswapV3Pool.json");
const fs = require('fs');
const JSBI = require('JSBI');
const API_ALCHEMY_ARBITRUM_RINKEBY = 'https://arb-rinkeby.g.alchemy.com/v2/<API KEY>';
const POOL_ADDRESS_MYTOKEN_WETH = '0xc69e7AE1073DD8184FcF6dBfc27ba97d1524716A';
const mnemonic = fs.readFileSync("./.mnemonics").toString().trim();
const hdprovider = new HDWalletProvider(mnemonic, API_ALCHEMY_ARBITRUM_RINKEBY);
const provider = new ethers.providers.Web3Provider(hdprovider);
const owner = hdprovider.addresses[0];
var web3 = new Web3(hdprovider);
const Contract = web3.eth.Contract;
const router = new AlphaRouter({
chainId: 421611,
provider: provider
});
async function main() {
const MyPool = new Contract(ABI_UNISWAP_POOL_V3.abi, POOL_ADDRESS_MYTOKEN_WETH);
const [factory, token0, token1, fee, tickSpacing, liquidity, maxLiquidityPerTick] =
await Promise.all([MyPool.methods.factory().call(),
MyPool.methods.token0().call(),
MyPool.methods.token1().call(),
MyPool.methods.fee().call(),
MyPool.methods.tickSpacing().call(),
MyPool.methods.liquidity().call(),
MyPool.methods.maxLiquidityPerTick().call()
]);
const tokenA = new Token(3, token0, 2, "MTK", "MyToken");
const tokenB = new Token(3, token1, 18, "WETH", "Wrapped Ether");
var amountOut = 2000;
amountOut = CurrencyAmount.fromRawAmount(tokenA, JSBI.BigInt(amountOut.toString()));
const slippageTolerance = new Percent(5, 100);
const deadline = Date.now() + 15000;
const route = await router.route(
amountOut,
tokenB,
TradeType.EXACT_OUTPUT, {
recipient: owner,
slippageTolerance: slippageTolerance,
deadline: deadline
}
);
hdprovider.engine.stop();
}
main();
I see two things are not right in this code:
First is the amountOut that you are passing to router.route should be converted to wei
const amountOutInWei=ethers.utils.parseUnits(amountOut.toString(),decimals)
// amountOutInWei should be converted to currentAmount
const currencyAmount= CurrencyAmount.fromRawAmount(tokenA,JSBI.BigInt(amountOutInWei))
currencyAmount should be passed to the router.route(currencyAmount,..)
Second issue deadline must be in seconds.
const deadline=Math.floor(Date.now() / 1000)+10*60 // addded 10 minutes

Opensea listing through Opensea-js is not working

I have created a nft and is listed in OpenSea. Now I am trying to create sell order of my item through opensea-js sdk. Unfortunately it is not working. Do not know where I am making a mistake. Also I am not sure on base derivation path. Below is my code to create sell order. Pls help me resolving this.
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 = "accuse never ....";
const NFT_CONTRACT_ADDRESS = "0x6C317E7dE3e8823BBc308a2912Ba6F24587fc167";
const OWNER_ADDRESS = "0x589a1532AAaE84e38345b58C11CF4697Ea89A866";
API_KEY = "";
const infuraRpcSubprovider = new RPCSubprovider({
rpcUrl: "https://rinkeby.infura.io/v3/c0e4482bdf9e4f539692666cd56ef6e4"
});
const BASE_DERIVATION_PATH = `44'/60'/0'/0`;
const mnemonicWalletSubprovider = new MnemonicWalletSubprovider({
mnemonic: MNEMONIC,
baseDerivationPath: BASE_DERIVATION_PATH,
chainId: 4
});
const providerEngine = new Web3ProviderEngine();
providerEngine.addProvider(mnemonicWalletSubprovider);
providerEngine.addProvider(infuraRpcSubprovider);
providerEngine.start();
const seaport = new OpenSeaPort(
providerEngine,
{
networkName: Network.Rinkeby,
apiKey: API_KEY,
},
(arg) => console.log(arg)
);
async function main() {
console.log("Auctioning an item for a fixed price...");
const fixedPriceSellOrder = await seaport.createSellOrder({
asset: {
tokenId: "3",
tokenAddress: NFT_CONTRACT_ADDRESS,
},
startAmount: 0.0001,
expirationTime: 0,
accountAddress: OWNER_ADDRESS,
}) ;
console.log("fixedPriceSellOrder") ;
}
main();
This has been resolved. I have changed the HDProvider to #truffle/hdwallet-provider. Now I could see the listing in opensea after createSellOrder through opensea-js.
This link helped me to get this resolved

Trying to send the ltc coin uisng Bitgo js

I want to send the ltc using bitGo js api, but its not wokring there is issue of the amount.It works well for btc but not for ltc.I have tried to covert the amount into satoshi and litoshi but till it not working.Following is my code:
const BitGoJS = require('../../src/index');
const bitgo = new BitGoJS.BitGo({ env: 'test' });
const Promise = require('bluebird');
const coin = 'tltc';
const basecoin = bitgo.coin(coin);
// TODO: set your access token here
const accessToken = null;
const walletId = '5941ce2db42fcbc70717e5a898fd1595';
// TODO: set your passphrase here
const walletPassphrase = null;
Promise.coroutine(function *() {
bitgo.authenticateWithAccessToken({ accessToken: accessToken });
const walletInstance = yield basecoin.wallets().get({ id: walletId });
const newReceiveAddress1 = yield walletInstance.createAddress();
const newReceiveAddress2 = yield walletInstance.createAddress();
const transaction = yield walletInstance.sendMany({
recipients: [
{
amount: '12341234', //not getting how to convert the amount here
address: newReceiveAddress1.address
},
],
walletPassphrase: walletPassphrase
});
const explanation = basecoin.explainTransaction({ txHex: transaction.tx });
console.log('Wallet ID:', walletInstance.id());
console.log('Current Receive Address:', walletInstance.receiveAddress());
console.log('New Transaction:', JSON.stringify(transaction, null, 4));
console.log('Transaction Explanation:', JSON.stringify(explanation, null, 4));
})();
Please suggest some solution how to resolve the amount issue while passing to the api for send method in bitGo js

Resources