Opensea listing through Opensea-js is not working - node.js

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

Related

tronWeb getAccount returns null

(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)

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.

Google Vision Automl fs.readFileSync alternative

I'm playing around with Google Vision autoML in react and I'm trying to figure out a way to change fs.readFileSync to an online url. I've used https, request and even url in node.js but I still can't figure out a way to make it read from a url source. Any help is appreciated, thank you
const projectId = "abc"
const location = "abc"
const modelId = "abc"
const filePath = "./test-pics/7.jpg"
const { PredictionServiceClient } = require("#google-cloud/automl").v1
const https = require("https")
const request = require("request")
const url = require("node:url")
const fs = require("fs")
const client = new PredictionServiceClient({
keyFilename: "./vision-private-key.json",
})
const imageURL = "https://cdn.filestackcontent.com/IJ0kViHQQyiwQTVaFH66"
// Read the file content for translation.
const content = fs.readFileSync(filePath)
const content1 = https.get(imageURL)
const content2 = request.get(
"https://cdn.filestackcontent.com/IJ0kViHQQyiwQTVaFH66"
)
async function predict() {
const request = {
name: client.modelPath(projectId, location, modelId),
payload: {
image: {
imageBytes: content,
},
},
}
const [response] = await client.predict(request)
for (const annotationPayload of response.payload) {
console.log(`type of vehicle: ${annotationPayload.displayName}`)
const carType = annotationPayload.displayName
console.log(carType)
}
}
predict()

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

Google Vision | Vietnamese: Low Quality OCR Results

Background
Using Google Vision API (with Node) to recognize Vietnamese text, the result is lacking quality. There are some (not all but some) tone markers as well as vowel signifies missing.
Compared to their online demo, which returns a decent result (scroll down for live demo):
https://cloud.google.com/vision/
(As I do not have a company account with them, I cannot ask Google directly.)
Question
Can I tweak my request to get better results?
I already set the language hint to "vi" and tried to combine it with "en". I also tried the more specific "vi-VN".
Example Image
https://www.tecc.org/Slatwall/custom/assets/images/product/default/cache/j056vt-_800w_800h_sb.jpg
Example Code
const fs = require("fs");
const path = require("path");
const vision = require("#google-cloud/vision");
async function quickstart() {
let text;
const fileName = "j056vt-_800w_800h_sb.jpg";
const imageFile = fs.readFileSync(fileName);
const image = Buffer.from(imageFile).toString("base64");
const client = new vision.ImageAnnotatorClient();
const request = {
image: {
content: image
},
imageContext: {
languageHints: ["vi", 'en']
}
};
const [result] = await client.textDetection(request);
for (const tmp of result.textAnnotations) {
text += tmp.description + '\n';
}
const out = path.basename(fileName, path.extname(fileName)) + ".txt";
fs.writeFileSync(out, text);
}
quickstart();
Solution
// $env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
const fs = require("fs");
const path = require("path");
const vision = require("#google-cloud/vision");
async function quickstart() {
let text = '';
const fileName = "j056vt-_800w_800h_sb.jpg";
const imageFile = fs.readFileSync(fileName);
const image = Buffer.from(imageFile).toString("base64");
const client = new vision.ImageAnnotatorClient();
const request = {
image: {
content: image
},
imageContext: {
languageHints: ["vi-VN"]
}
};
const [result] = await client.documentTextDetection(request);
// OUTPUT METHOD A
for (const tmp of result.textAnnotations) {
text += tmp.description + "\n";
}
console.log(text);
const out = path.basename(fileName, path.extname(fileName)) + ".txt";
fs.writeFileSync(out, text);
// OUTPUT METHOD B
const fullTextAnnotation = result.fullTextAnnotation;
console.log(`Full text: ${fullTextAnnotation.text}`);
fullTextAnnotation.pages.forEach(page => {
page.blocks.forEach(block => {
console.log(`Block confidence: ${block.confidence}`);
block.paragraphs.forEach(paragraph => {
console.log(`Paragraph confidence: ${paragraph.confidence}`);
paragraph.words.forEach(word => {
const wordText = word.symbols.map(s => s.text).join("");
console.log(`Word text: ${wordText}`);
console.log(`Word confidence: ${word.confidence}`);
word.symbols.forEach(symbol => {
console.log(`Symbol text: ${symbol.text}`);
console.log(`Symbol confidence: ${symbol.confidence}`);
});
});
});
});
});
}
quickstart();
This question is already answered in this one.
In summary, the Demo is in this case probably using the DOCUMENT_TEXT_DETECTION, which can sometimes make a more thorough strings extraction, while you are using TEXT_DETECTION.
You can try to make a client.document_text_detection request instead of client.textDetection and you will probably get results closer to the Demo.
If you want to read to the related documentation you can find it here.
I hope this resolves your question!

Resources