Uniswap USDC=> ETH exchange - javascript

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

Related

Transaction Fail when trying to swap on Uniswap V3 programmatically

I'm trying to create a script to execute a swap on Uniswap V3.
The code below works perfectly well on the Goerli Testnet Network but NOT on Mainnet.
In order to make in run on mainnet:
i've changed the tokens addresses to match the mainnet ones and also changed the INFURA_URL to the mainnet url but I keep getting failed transactions..
const address0 = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2'
const address1 = '0x6B175474E89094C44Da98b954EedeAC495271d0F'
Seems like the error might come from the swapRouterAddress but not sure..
Moreover, when I execute the swap manually using Uniswap website, i can see that the swap was executed using Uniswap V3: Router 2, but even if I use this Router Address on my script the transaction keep failing..
Does anyone knows how to solve this ?
Thanks a lot !
const { ethers } = require('ethers')
const { abi: IUniswapV3PoolABI } = require('#uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Pool.sol/IUniswapV3Pool.json')
const { abi: SwapRouterABI} = require('#uniswap/v3-periphery/artifacts/contracts/interfaces/ISwapRouter.sol/ISwapRouter.json')
const { abi: UniswapV3Factory } = require('#uniswap/v3-core/artifacts/contracts/UniswapV3Factory.sol/UniswapV3Factory.json')
const { getPoolImmutables, getPoolState } = require('./helpers')
const ERC20ABI = require('./abi.json')
require('dotenv').config()
const INFURA_URL_TESTNET = process.env.INFURA_URL_TESTNET
// Wallets
const WALLETS = [process.env.WALLET_ADDRESS_1];
var SECRET = new Object();
SECRET[process.env.WALLET_ADDRESS_1] = process.env.WALLET_SECRET_1;
// Provider
const provider = new ethers.providers.JsonRpcProvider(INFURA_URL_TESTNET) // Goerli
const swapRouterAddress = '0xE592427A0AEce92De3Edee1F18E0157C05861564'
// Wrapped Ether
const name0 = 'Wrapped Ether'
const symbol0 = 'WETH'
const decimals0 = 18
const address0 = '0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6'
// Token info
const name1 = 'Token'
const decimals1 = 18
const address1 = '0x11fE4B6AE13d2a6055C8D9cF65c55bac32B5d844' // DAI
// SWAP
const factoryAddress = '0x1F98431c8aD98523631AE4a59f267346ea31F984'
async function buy(WETH_amount) {
const factoryContract = new ethers.Contract(
factoryAddress,
UniswapV3Factory,
provider
)
const poolAddress = await factoryContract.getPool(address0, address1, 500)
for (const WALLET of WALLETS)
{
const poolContract = new ethers.Contract(
poolAddress,
IUniswapV3PoolABI,
provider
)
const immutables = await getPoolImmutables(poolContract)
const state = await getPoolState(poolContract)
var WALLET_SECRET = SECRET[WALLET];
const wallet = new ethers.Wallet(WALLET_SECRET)
const connectedWallet = wallet.connect(provider)
const swapRouterContract = new ethers.Contract(
swapRouterAddress,
SwapRouterABI,
provider
)
const inputAmount = WETH_amount
// .001 => 1 000 000 000 000 000
const amountIn = ethers.utils.parseUnits(
inputAmount.toString(),
decimals0
)
const params = {
tokenIn: immutables.token1,
tokenOut: immutables.token0,
fee: immutables.fee,
recipient: WALLET,
deadline: Math.floor(Date.now() / 1000) + (60 * 5),
amountIn: amountIn,
amountOutMinimum: 0,
sqrtPriceLimitX96: 0,
}
const transaction = swapRouterContract.connect(connectedWallet).exactInputSingle(
params,
{
gasLimit: ethers.utils.hexlify(1000000)
}
).then(transaction => {
console.log(transaction)
})
}
}
// MAIN
buy(WETH_amount_=0.001)
Note that the token address for WETH is different on mainnet - your code has the address for WETH on Goerli. See https://docs.uniswap.org/protocol/reference/deployments for some token addresses

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

ethers.js swapExactTokensForTokens error transferFrom failed

I have a problem about pancakeswap ethers.js code on BSC testnet. My tx always failed with error "Fail with error 'TransferHelper::transferFrom: transferFrom failed'"
My Balance are 0.4317 BNB, 20 BUSD and 0.074 ETH
Can someone helpme?, I'm strucking for 2 days
const ethers = require('ethers');
const addresses = {
WBNB: '0xae13d989dac2f0debff460ac112a837c89baa7cd', //Testnet
BUSD: '0x78867BbEeF44f2326bF8DDd1941a4439382EF2A7', //Testnet
router: '0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3',
recipient: '{Censored}'
}
const privateKey = '{Censored}';
const provider = new ethers.providers.JsonRpcProvider('https://data-seed-prebsc-1-s1.binance.org:8545/'); // TESTNET
const wallet = new ethers.Wallet(privateKey, provider);
const account = wallet.connect(provider);
const router = new ethers.Contract(
addresses.router,
[
'function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)',
'function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)',
'function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts)',
'function swapExactETHForTokensSupportingFeeOnTransferTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable'
],
account
);
const wbnb = new ethers.Contract(
addresses.WBNB,
[
'function approve(address spender, uint256 amount) external returns (bool)',
],
account
);
const WBNBAmountToPay = ethers.utils.parseUnits('1');
const init = async () => {
const amountIn = ethers.utils.parseUnits('0.001', 'ether');
const gas = {
gasPrice: ethers.utils.parseUnits('50', 'gwei'),
gasLimit: '2000000'
};
const tx = await wbnb.approve(addresses.router, WBNBAmountToPay.toString(), gas);
const receipt = await tx.wait();
console.log('Transaction receipt');
console.log(receipt);
const amounts = await router.getAmountsOut(amountIn, [addresses.WBNB, addresses.BUSD]);
const amountOutMin = amounts[1].sub(amounts[1].div(10));
console.log('Swapping',
ethers.utils.formatUnits(amountIn), 'WBNB for ',
ethers.utils.formatUnits(amountOutMin), 'BUSD'
);
const tx2 = await router.swapExactTokensForTokens(
amountIn,
amountOutMin,
[addresses.WBNB, addresses.BUSD],
addresses.recipient,
Date.now() + 1000 * 60 * 10,
gas
);
const receipt2 = await tx2.wait();
console.log('Transaction receipt');
console.log(receipt2);
}
init();
Sample error tx here "https://testnet.bscscan.com/tx/0xd17e13cec5778226414b191a5f274e7ba4f59c8f683979eb9c1aa17077aead2f"
if you are using swapExactTokensForTokens you need to approve the router contract before call the function. But from the code above you can use swapExactETHForTokensSupportingFeeOnTransferTokens instead

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

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