How to complete swap method for JustSwap smart-contract - javascript

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

Related

Getting an ENS error when interacting with a Smart Contract using ethers library

I everyone, I'm trying to call a function called 'safeMint' on an ERC721 contract deployed on Rinkeby testnet but I'm getting this error:
Error: resolver or addr is not configured for ENS name (argument="name", value="", code=INVALID_ARGUMENT, version=contracts/5.5.0)
This is the code I'm using to call the function
const mintNFT = async () => {
const {ethereum} = window;
if(isMetaMaskInstalled) {
try {
const abi = require('../contracts/Animals.json').abi;
console.log(abi);
const accounts = await ethereum.request({ method: 'eth_accounts' });
setAccount(accounts[0]);
const web3Provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = web3Provider.getSigner();
const contractWrite = new ethers.Contract('0x53Ea14980c8326E93a9F72889171c1e03d4aD6Ce', abi, signer);
let trx = await contractWrite.safeMint(account, props.cidOfJsonInIpfs);
console.log(trx);
} catch(err) {
console.log(err);
}
}
}
I've tried to print the parameters passed but they seem to be right, what am I doing wrong?
I solved it with the following code
const mintNFT = async () => {
const {ethereum} = window;
if(isMetaMaskInstalled) {
try {
const abi = require('../contracts/Animals.json').abi;
console.log(abi);
const accounts = await ethereum.request({ method: 'eth_accounts' });
const web3Provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = web3Provider.getSigner(accounts[0]);
console.log(signer._address)
const contractWrite = new ethers.Contract('0x53Ea14980c8326E93a9F72889171c1e03d4aD6Ce', abi, signer);
let trx = await contractWrite.safeMint(accounts[0], `https://gateway.pinata.cloud/ipfs/${props.cidOfFile}`);
let receipt = await trx.wait();
console.log(receipt);
} catch(err) {
console.log(err);
}
}
What I was missing: I was using setState function to set the 'account' state variable with the first account of metamask, instead, I started using account[0] directly and it worked!
I will accept this as solution in 2 days

Uniswap USDC=> ETH exchange

Trying to exchange USDC to ETH vith Uniswap and Ethers, but getting errors all the time.
async function swapUsdcToEth(amount, walledAddress) {
const usdc = await Fetcher.fetchTokenData(chainId, '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48');
const eth = await Fetcher.fetchTokenData(chainId, '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2');
const pair = await Fetcher.fetchPairData(usdc, eth);
const route = new Route([pair], usdc);
const amountIn = new TokenAmount(usdc, amount);
const trade = new Trade(route, amountIn, TradeType.EXACT_INPUT);
const slippageTolerance = new Percent('50', '10000');
const value = ethers.BigNumber.from(trade.inputAmount.raw.toString()).toHexString();
const amountOutMin = ethers.BigNumber.from(trade.minimumAmountOut(slippageTolerance).raw.toString()).toHexString();
const deadline = Math.floor(Date.now() / 1000) + 60 * 20;
const uniswapRouterV2Address = '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D';
const provider = new ethers.providers.JsonRpcProvider('https://mainnet.infura.io/v3/b9fkdmkdkdv4937b52ea9637cf1d1bd');
const signer = new ethers.Wallet(walledAddress, provider);
const uniswap = new ethers.Contract(
uniswapRouterV2Address,
['function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)'],
signer
);
try {
const tx = await uniswap.swapExactTokensForETH(value, amountOutMin, [walledAddress], walledAddress, deadline);
const receipt = await tx.wait();
console.log('transaction was mined in block', receipt.blockNumber);
} catch (e) {
console.log(e);
}
}
Receiving errors like that: ' Error: cannot estimate gas; transaction may fail or may require manual gas limit '. What I am doing wrong?
So it looks like possibly a few things. Have you approved your token to be spent by the router?
Also I'm not seeing any gas settings in there
here is a working version that I have modified to make work ( This is setup to test on a mainnet fork, however it's using live data (as the AlphaRouter is only for mainnet live so the live data and the fork data will change with time and cause trade errors, so reset fork before using)
to make main net only take out local provider and change all providers to main net provider.
USE WITH CAUTION, I'M NOT PERFECT AND GUARANTEE NOTHING : Check slippage and all variables
This is built As a TOKEN to TOKEN Exact_Input swap with WETH deposit of 1 ETH.
To use ETH you can remove Weth deposit and token in approval and use the BigNumber.from(typedValueParsed) as the value of the transaction instead of 0
As I don't know EtherJS to well the Gas Price and Gas Limit for the Deposit and approval is a flat 100 gwei & 300k Limit, and should be modified for current network gas price and estimated gas Limit.
import { AlphaRouter } from '#uniswap/smart-order-router'
import { Token, CurrencyAmount } from '#uniswap/sdk-core'
import { JSBI, Percent } from "#uniswap/sdk";
import { ethers, BigNumber } from "ethers";
const V3_SWAP_ROUTER_ADDRESS = "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45";
const TokenInput = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
const TokenOutput = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
const web3Provider = new ethers.providers.JsonRpcProvider("https://eth-mainnet.alchemyapi.io/v2/");
const web3 = new ethers.providers.JsonRpcProvider("http://127.0.0.1:8545/");
const privateKey = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
const wallet = new ethers.Wallet(privateKey,web3);
const address = wallet.address;
import * as fs from 'fs';
let UniV3RouterAbi = fs.readFileSync('NewUniRouter.json');
const V3routerAbi = JSON.parse(UniV3RouterAbi);
let ERC20Abi = fs.readFileSync('ERC20.json');
const ERC20 = JSON.parse(ERC20Abi);
let WETHAbij = fs.readFileSync('WETHAbi.json');
const WETHAbi = JSON.parse(WETHAbij);
async function log(inpt){
console.log(inpt);
console.log("");
}
async function TokBal(tokens){
var ERC20contract = new ethers.Contract(tokens, ERC20, web3);
var myERC20bal = await ERC20contract.balanceOf(wallet.address);
return myERC20bal;
}
async function Deposit(amt){
var WethC = new ethers.Contract(TokenInput, WETHAbi, web3);
var datac = await WethC.populateTransaction["deposit"]();
var ncn = await wallet.getTransactionCount();
const transaction = {
data: datac.data,
nonce: ncn,
to: TokenInput,
value: BigNumber.from(amt),
from: wallet.address,
gasPrice: '0x174876e800',
gasLimit: '0x493e0',
};
const signedTx = await wallet.signTransaction(transaction);
const txHash = await web3.sendTransaction(signedTx);
log(txHash.hash);
}
async function Approve(Toked, amt){
var WethC = new ethers.Contract(Toked, ERC20, web3);
var datac = await WethC.populateTransaction["approve"](V3_SWAP_ROUTER_ADDRESS, amt);
var ncn = await wallet.getTransactionCount();
const transaction = {
data: datac.data,
nonce: ncn,
to: Toked,
value: BigNumber.from("0"),
from: wallet.address,
gasPrice: '0x174876e800',
gasLimit: '0x493e0',
};
const signedTx = await wallet.signTransaction(transaction);
const txHash = await web3.sendTransaction(signedTx);
log(txHash.hash);
var appFor = await WethC.callStatic.allowance(wallet.address, V3_SWAP_ROUTER_ADDRESS);
log("Approved : "+appFor.toString());
}
const router = new AlphaRouter({ chainId: 1, provider: web3Provider });
const WETH = new Token(
router.chainId,
'0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
18,
'WETH',
'Wrapped Ether'
);
const USDC = new Token(
router.chainId,
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
6,
'USDC',
'USD//C'
);
const typedValueParsed = '1000000000000000000';
const wethAmount = CurrencyAmount.fromRawAmount(WETH, JSBI.BigInt(typedValueParsed));
const IO = "Exact_Input"
const TradeType = IO == "Exact_Input" ? 0 : 1;
const route = await router.route(
wethAmount,
USDC,
TradeType,
{
recipient: wallet.address,
slippageTolerance: new Percent(5, 100),
deadline: Math.floor(Date.now()/1000 +1800)
}
);
var Ebal = await web3.getBalance(wallet.address);
log("Wallet Balance : "+Ebal.toString());
var tbal = await TokBal(TokenOutput);
log("Token Out Balance : "+tbal.toString());
await Deposit("1000000000000000000");
await Approve(TokenInput,"1000000000000000000");
var tbalW = await TokBal(TokenInput);
log("Token In Balance : "+tbalW.toString());
log(`Quote Exact In: ${route.quote.toFixed(wethAmount.currency === WETH ? USDC.decimals : WETH.decimals)}`);
log(`Gas Adjusted Quote In: ${route.quoteGasAdjusted.toFixed(wethAmount.currency === WETH ? USDC.decimals : WETH.decimals)}`);
var nc = await wallet.getTransactionCount();
const transaction = {
data: route.methodParameters.calldata,
nonce: nc,
to: V3_SWAP_ROUTER_ADDRESS,
value: BigNumber.from(0),
from: wallet.address,
gasPrice: BigNumber.from(route.gasPriceWei),
gasLimit: BigNumber.from(route.estimatedGasUsed).add(BigNumber.from("50000")),
};
const signedTx = await wallet.signTransaction(transaction);
const PretxHash = ethers.utils.keccak256(signedTx);
const txHash = await web3.sendTransaction(signedTx)
log(txHash.hash);
var Ebal = await web3.getBalance(wallet.address);
log("Wallet Balance : "+Ebal.toString());
var tbal = await TokBal(TokenOutput);
log("Token Out Balance : "+tbal.toString());
var tbalW = await TokBal(TokenInput);
log("Token In Balance : "+tbalW.toString());
to get ETH use this in place of the output token
outPutAddress === WETH9[chainId].address ? nativeOnChain(chainId) : outPutToken,
EDIT>>>>>>>>>>
modified for new versions
import { ethers } from 'ethers'
import {AlphaRouter, ChainId, SwapType, nativeOnChain} from '#uniswap/smart-order-router'
import { TradeType, CurrencyAmount, Percent, Token } from '#uniswap/sdk-core'
import { TickMath } from '#uniswap/v3-sdk';
import JSBI from 'jsbi';
import bn from 'bignumber.js'
async function main() {
const MY_ADDRESS = "<ADDRESS>";
const web3Provider = new ethers.providers.JsonRpcProvider('https://eth-mainnet.alchemyapi.io/v2/<RPC_KEY>')
const router = new AlphaRouter({ chainId: 1, provider: web3Provider });
const WETH = new Token(
1,
'0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
18,
'WETH',
'Wrapped Ether'
);
const USDC = new Token(
ChainId.MAINNET,
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
6,
'USDC',
'USD//C'
);
const AAVE = new Token(
ChainId.MAINNET,
'0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9',
18,
'AAVE',
'AAVE'
);
const options = {
recipient: MY_ADDRESS,
slippageTolerance: new Percent(10, 1000),
deadline: Math.floor(Date.now() / 1000 + 1800),
type: SwapType.SWAP_ROUTER_02,
}
const typedValueParsed = '10000000000000000000'
const route = await router.route(
CurrencyAmount.fromRawAmount(
AAVE,
typedValueParsed.toString()
),
nativeOnChain(ChainId.MAINNET),
TradeType.EXACT_INPUT,
options
)
console.log(`Quote Exact In: ${route.quote.toFixed(route.quote.currency.decimals)}`);
console.log(`Gas Adjusted Quote In: ${route.quoteGasAdjusted.toFixed(route.quote.currency.decimals)}`);
console.log(`Gas Used USD: ${route.estimatedGasUsedUSD.toFixed(2)}`);
console.log(route.methodParameters.calldata);
}
main()

Apify - How to Enqueue URL Variations Efficiently

I am creating a new actor in Apify with Cheerio to read an input file of URLs and return primarily two items: (1) the HTTP status code and (2) the HTML title. As part of our process, I would like to be able to try up to 4 variations of each input URL, such as:
HTTP://WWW.SOMEURL.COM
HTTPS://WWW.SOMEURL.COM
HTTP://SOMEURL.COM
HTTPS://SOMEURL.COM
If one of the 4 variations is successful, then the process should ignore the other variations and move to the next input URL.
I read the original input list into a RequestList, and then would like to create the variations in a RequestQueue. Is this the most efficient way to do it? Please see code below, and thank you!
const Apify = require('apify');
const {
utils: { enqueueLinks },
} = Apify;
const urlParse = require('url');
Apify.main(async () => {
const input = await Apify.getInput();
const inputFile = input.inputFile;
console.log('INPUT FILE: ' + inputFile);
const requestList = await Apify.openRequestList('urls', [
{ requestsFromUrl: inputFile, userData: { isFromUrl: true } },
]);
const requestQueue = await Apify.openRequestQueue();
const proxyConfiguration = await Apify.createProxyConfiguration();
const handlePageFunction = async ({ $, request, response }) => {
let parsedHost = urlParse.parse(request.url).host;
let simplifiedHost = parsedHost.replace('www.', '');
const urlPrefixes = ['HTTP://WWW.', 'HTTPS://WWW.', 'HTTP://', 'HTTPS://'];
let i;
for (i = 0; i < urlPrefixes.length; i++) {
let newUrl = urlPrefixes[i] + simplifiedHost;
console.log('NEW URL: ' + newUrl);
await requestQueue.addRequest({ url: newUrl });
}
console.log(`Processing ${request.url}`);
const results = {
inputUrl: request.url,
httpCode: response.statusCode,
title: $('title').first().text().trim(),
responseUrl: response.url
};
await Apify.pushData(results);
};
const crawler = new Apify.CheerioCrawler({
proxyConfiguration,
maxRequestRetries: 0,
handlePageTimeoutSecs: 60,
requestTimeoutSecs: 60,
requestList,
requestQueue,
handlePageFunction,
handleFailedRequestFunction: async ({ request }) => {
await Apify.pushData({ inputUrl: request.url, httpCode: '000', title: '', responseUrl: ''});
}
});
await crawler.run();
});
you should create your URL list beforehand. the handlePageFunction is only used for the actual scraping part, and you should only have the Apify.pushData there:
//...
const initRequestList = await Apify.openRequestList('urls', [
{ requestsFromUrl: inputFile },
]);
const parsedRequests = [];
let req;
while (req = await initRequestList.fetchNextRequest()) {
const parsedHost = urlParse.parse(req .url).host;
const simplifiedHost = parsedHost.replace('www.', '');
const urlPrefixes = ['HTTP://WWW.', 'HTTPS://WWW.', 'HTTP://', 'HTTPS://'];
for (let i = 0; i < urlPrefixes.length; i++) {
let newUrl = urlPrefixes[i] + simplifiedHost;
console.log('NEW URL: ' + newUrl);
parsedRequests.push({
url: newUrl,
userData: { isFromUrl: true }
});
}
}
const requestList = await Apify.openRequestList('starturls', parsedRequests);
//...
const crawler = new Apify.CheerioCrawler({
proxyConfiguration,
maxRequestRetries: 0,
handlePageTimeoutSecs: 60,
requestTimeoutSecs: 60,
handlePageFunction,
requestList,
handleFailedRequestFunction: async ({ request }) => {
await Apify.pushData({ inputUrl: request.url, httpCode: '000', title: '', responseUrl: ''});
}
});
//...
requestsFromUrl is a greedy function that tries to parse all URLs from to the given resource. so you'll have to perform the processing as an additional step.

How to call balanceOf() method for non published ABI

I'm trying to call balanceOf() method on a specific Tron contract (TYukBQZ2XXCcRCReAUguyXncCWNY9CEiDQ), but what I get is Failed to execute . If I do not provide the parameters I get Invalid argument count provided - meaning at some level it works for this contract.
What is interesting it works well on contracts other than the ones created with JustSwap Factory contract eg. https://tronscan.io/#/contract/TYukBQZ2XXCcRCReAUguyXncCWNY9CEiDQ/code .
The code includes the standard TRC20 methods - including balanceOf() - I'm stuck and tried all that's possible form my side, but let's just say I'm not fluent in tronweb api.
My code:
export const getDataToken = async (contractAddress, account, account2) => {
try {
const instance = await window.tronWeb.contract(
[
{
constant: true,
inputs: [{ name: "owner", type: "address" }],
name: "balanceOf",
outputs: [{ name: "", type: "uint256" }],
payable: false,
stateMutability: "view",
type: "function"
}
],
contractAddress
);
console.log(instance);
if (instance.balanceOf) {
console.log("dadadad if");
const tokenBalance = await instance.balanceOf(account).call();
const tokenBalance2 = await instance.balanceOf(account2).call();
return {
tokenBalance: (tokenBalance / Math.pow(10, 18)).toString(),
tokenContract: instance,
tokenBalance2: (tokenBalance2 / Math.pow(10, 18)).toString()
};
}
} catch (message) {
console.log("error getData :" + message);
}
};
const { tokenBalance, tokenContract, tokenBalance2 } = getDataToken(
"TYukBQZ2XXCcRCReAUguyXncCWNY9CEiDQ",
"TL4HzzxGMc1LMfs3XCi4yTJikaBVubz5y4",
"TTFp171XD4JdUB33sDq2ydXJyUEEZjNhLD"
);
This function can help (example for getting JustSwap pair price):
async function takePrice(contractAddress, token){
var functionSelector = 'getTokenToTrxInputPrice(uint256)';
var parameter = [
{
type: 'uint256',
value: token
}
]
var options = {};
transaction = await window.tronWeb.transactionBuilder.triggerConstantContract(contractAddress, functionSelector, options, parameter);
return window.tronWeb.BigNumber("0x"+transaction['constant_result'][0]);
}
priceUSDTTRX = window.tronWeb.fromSun(await takePrice(USDTTRX_ADDRESS, "1000000"));
priceSomeTone18TRX = window.tronWeb.fromSun(await takePrice(SomeTone18TRX_ADDRESS, "1"+"0".repeat(18)));
I have good result:
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 parameter = [{type:`uint256`,value: 10000000}];
const tx = await tronWebLocal.transactionBuilder.triggerConstantContract(contractToken, `trxToTokenSwapInput(uint256,uint256)`, {}, parameter);
console.log(tx);
} catch (e) {
console.log(e);
}
};
startJustSwap();
try const tokenBalance = await instance.balanceOf(account).call({ _isConstant: true });
It works for me.
transactionBuilder.triggerConstantContract works too, but mine is simpler

Lowdb return undefined

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;

Categories