Web3 | TransferFrom() transactions always Failed - solidity

I'm trying to send Custom ERC20 Token to Owner Wallet Address using transferFrom() function using Web3.js
However all the Transactions are failed. Which is the same problem occur on Remix IDE.
Some answers on stackOverflow here says that the approve() is needed to call first before the transferFrom() function. so, I tried on Remix frist but I got the same problem. And then tried with using Web3.js like below.
const myContract = new web3.eth.Contract(abi);
const amount = sendAmount;
let address = myAddress;
myContract.options.address = contractAddress;
myContract.options.from = TokenOwner;
let options = myContract.options;
let data1 = myContract.methods.approve(address, amount).encodeABI();
let data2 = myContract.methods.transferFrom(address, TokenOwner, amount).encodeABI();
const ethAccount = fromPrivateKey(toBuffer("0x..."));
const fromPrivateKeyBuffer = ethAccount.getPrivateKey();
web3.eth.getTransactionCount(TokenOwner, (err, count) => {
if (err) return;
const txData = {
chainId: 0x03,
gasPrice: web3.utils.toHex(42000000000),
gasLimit: web3.utils.toHex(90000),
to: contractAddress,
from: TokenOwner,
value: 0x0,
nonce: web3.utils.toHex(count),
data: data1
};
const tx = new ethTx(txData);
tx.sign(fromPrivateKeyBuffer);
const serializedTx = tx.serialize().toString("hex");
if (!serializedTx) {
return;
} else {
web3.eth.sendSignedTransaction(`0x${serializedTx}`, (err, MuiTXHash) => {
console.log("err : ", err, "Data1-MuiTXHash : ", MuiTXHash);
// START DATA2
web3.eth.getTransactionCount(TokenOwner, (err, count) => {
if (err) return;
const txData2 = {
chainId: 0x03,
gasPrice: web3.utils.toHex(42000000000),
gasLimit: web3.utils.toHex(90000),
to: contarctAddress,
from: TokenOwner,
value: 0x0,
nonce: web3.utils.toHex(count + 1),
data: data2
};
const tx2 = new ethTx(txData2);
tx2.sign(fromPrivateKeyBuffer);
const serializedTx2 = tx2.serialize().toString("hex");
if (!serializedTx2) {
return;
} else {
web3.eth.sendSignedTransaction(`0x${serializedTx2}`, (err, MuiTXHash2) => {
console.log("err : ", err, "Data2-MuiTXHash : ", MuiTXHash2);
});
}
});
// END DATA2
});
}
});
};
I got the two Transaction Hash return data and the TransferFrom() transaction is failed again.
What is the problem?
How can I make it success? I have to withdraw the custom ERC20 token from specific address to owner. so I have to use transferFrom() transaction.
Please let me know how to do. Thanks.

I guess the compiling on Remix had some errors so I created new solidity file with same code on it and deployed it. The new smart contract worked well and no errors occurred. The errors was not about my code. If someone's suffering like this problems, then create a new contract address and I don't recommend using 'At Address' on Remix. This is not work properly at all.

I was tried appove() + transferFrom () , allowance() on Solidity working well but on web3 not working error same as you

I guess the transferFrom function should be called by the spender (i.e the address to which the TokenOwner has approved to spend). So,
const txData2 = {
chainId: 0x03,
gasPrice: web3.utils.toHex(42000000000),
gasLimit: web3.utils.toHex(90000),
to: contarctAddress,
from: address, // spender's address
value: 0x0,
nonce: web3.utils.toHex(count + 1),
data: data2
};
And don't forget to use spender's privateKey to sign the txn and spender's address in getTransactionCount
Read Here : Ethereum Wiki
Hope it helps. :)

Related

How can I mint a Hedera token that is not owned by the contract I am using to mint it?

I want to mint a Hedera Token with a smart contract. This token is not owned by the smart contract I am writing. I have been told on the Discord to 'put the private key in the contract' but this is not very specific and feels weird. The mintToken function provided in the Hedera Token Service takes as parameter:
an address
an amount
some metadata in the case of NFTs.
It's not impossible to mint a token made of a smart contract with HederaTokenService.
You may use a smart contract to make a token on hedera like ERC-20 or ERC-721, they works but they are not recognized as tokens in hedera network.
You have to use HederaTokenService to make a token on hedera.
You can use a smart contract using HederaTokenService interface(its address is 0x167) or transactions like below.
You seems using HederaTokenService.sol.
The second parameter only has meaning when you mint a fungible token.
And the second parameter only has meaning when you mint a non-funtible token.
You can create a fungible token and mint like this.
IHederaTokenService.TokenKey[]
memory keys = new IHederaTokenService.TokenKey[](1);
// Set this contract as supply
keys[0] = getSingleKey(
KeyType.SUPPLY,
KeyValueType.CONTRACT_ID,
address(this)
);
IHederaTokenService.HederaToken memory token;
token.name = _name;
token.symbol = _symbol;
token.treasury = address(this);
token.memo = _memo;
token.tokenSupplyType = true; // set supply to FINITE
token.maxSupply = _maxSupply;
token.freezeDefault = false;
token.tokenKeys = keys;
token.expiry = createAutoRenewExpiry(address(this), _autoRenewPeriod); // Contract automatically renew by himself
(int256 responseCode, address createdToken) = HederaTokenService
.createFungibleToken(token, 0, _decimals);
if (responseCode != HederaResponseCodes.SUCCESS) {
revert("Failed to create fungible token");
}
tokenAddress = createdToken;
(int256 response, uint64 newSupply, ) = HederaTokenService.mintToken(
tokenAddress,
uint64(amount),
new bytes[](0)
);
Or a Non-fungible token like this.
IHederaTokenService.TokenKey[]
memory keys = new IHederaTokenService.TokenKey[](2);
// Set this contract as supply
keys[0] = getSingleKey(
KeyType.SUPPLY,
KeyValueType.CONTRACT_ID,
address(this)
);
keys[1] = getSingleKey(
KeyType.PAUSE,
KeyValueType.CONTRACT_ID,
address(this)
);
IHederaTokenService.HederaToken memory token;
token.name = _name;
token.symbol = _symbol;
token.treasury = address(this);
token.memo = _memo;
token.tokenSupplyType = true; // set supply to FINITE
token.maxSupply = int64(int256(_maxSupply));
token.freezeDefault = false;
token.tokenKeys = keys;
token.expiry = createAutoRenewExpiry(address(this), _autoRenewPeriod); // Contract automatically renew by himself
(int256 responseCode, address createdToken) = HederaTokenService
.createNonFungibleToken(token);
if (responseCode != HederaResponseCodes.SUCCESS) {
revert("Failed to create non-fungible token");
}
tokenAddress = createdToken;
(int256 response, uint64 newSupply, ) = HederaTokenService.mintToken(
tokenAddress,
uint64(amount),
new bytes[](0)
);
(int256 response, , int64[] memory serialNumbers) = HederaTokenService
.mintToken(tokenAddress, 0, metadata);
Here is a code of using transactions.
Hope it will help you.
const {
Client,
AccountId,
AccountBalanceQuery,
ContractExecuteTransaction,
ContractFunctionParameters,
ContractCallQuery,
TokenCreateTransaction,
Hbar,
HbarUnit,
TransactionRecord,
TokenSupplyType,
TokenType,
PrivateKey,
AccountCreateTransaction,
TokenId,
TokenMintTransaction,
TokenAssociateTransaction,
TokenDissociateTransaction,
TransferTransaction,
} = require("#hashgraph/sdk");
// Allow access to ourenv file variables
require("dotenv").config();
const print = require("./utils.js").print;
// Grab your account ID and private key from the .env file
const operatorAccountId = AccountId.fromString(process.env.MY_ACCOUNT_ID);
const operatorPrivateKey = PrivateKey.fromString(process.env.MY_PRIVATE_KEY);
const operatorPublicKey = operatorPrivateKey.publicKey;
const treasuryId = AccountId.fromString(process.env.TREASURY_ID);
const treasuryKey = PrivateKey.fromString(process.env.TREASURY_PVKEY);
const aliceId = AccountId.fromString(process.env.ALICE_ID);
const aliceKey = PrivateKey.fromString(process.env.ALICE_PVKEY);
const supplyKey = PrivateKey.fromString(process.env.SUPPLY_PVKEY);
const tokenId = TokenId.fromString("0.0.*");
// If we weren't able to grab it, we should throw a new error
if (operatorPrivateKey == null || operatorAccountId == null) {
throw new Error(
"environment variables MY_ACCOUNT_ID and MY_PRIVATE_KEY must be present"
);
}
// Create our connection to the Hedera network
// The Hedera JS SDK makes this really easy!
const client = Client.forTestnet();
// Set your client account ID and private key used to pay for transaction fees and sign transactions
client.setOperator(operatorAccountId, operatorPrivateKey);
async function printBalance(accountAlias, accountId) {
var currentBalance = await new AccountBalanceQuery()
.setAccountId(accountId.toString())
.execute(client);
console.log(
`Balance of ${accountAlias} (accountId ${accountId}): ${currentBalance.toString()}`
);
}
async function queryContract() {
const tx = new ContractCallQuery()
.setGas(300000)
.setContractId(tokenId.toString())
.setFunction(
"tokenURI",
new ContractFunctionParameters().addUint256(12)
// .addString("Golden")
);
// .setQueryPayment(Hbar.fromTinybars(300000));
const contractFunctionResult = await tx.execute(client);
console.log();
const ret_0 = contractFunctionResult.getString(0);
console.log(`return value :>> ${ret_0.toString()}`);
}
async function generateKey() {
const privateKey = await PrivateKey.generateED25519Async();
console.log(
`New key generated.\nPublic Key is ${privateKey.publicKey}\nPrivateKey is ${privateKey}`
);
return privateKey;
}
async function createAccount() {
const privateKey = await generateKey();
const transaction = new AccountCreateTransaction()
.setKey(privateKey.publicKey)
.setInitialBalance(new Hbar(1000));
//Sign the transaction with the client operator private key and submit to a Hedera network
const txResponse = await transaction.execute(client);
//Request the receipt of the transaction
const receipt = await txResponse.getReceipt(client);
//Get the account ID
const newAccountId = receipt.accountId;
console.log("The new account ID is " + newAccountId);
}
async function writeContract() {
const tx = new ContractExecuteTransaction()
.setContractId(contractId)
.setGas(300000) // Increase if revert
.setPayableAmount(Hbar.from(1.00000001)) // Increase if revert
.setFunction("pay", new ContractFunctionParameters().addString("Donate"));
const txRes = await tx.execute(client);
print("txResponse", txRes);
const receipt = await txRes.getReceipt(client);
print("recepit", receipt);
const txRec = await txRes.getRecord(client);
print("txRecord", txRec);
const value = txRec.contractFunctionResult.getUint256(0);
console.log(`First return value is: ${value.toString()}`);
const ret_0 = txRec.contractFunctionResult.getString(1);
console.log(`second return value is: ${ret_0.toString()}`);
// console.log(`First return value is: ${AccountId.fromSolidityAddress(ret_0)}`);
}
async function createToken() {
const transaction = await new TokenCreateTransaction()
.setTokenName("My Token")
.setTokenSymbol("MYT")
.setTokenType(TokenType.NonFungibleUnique)
.setDecimals(0)
.setInitialSupply(0)
.setTreasuryAccountId(treasuryId)
.setSupplyType(TokenSupplyType.Finite)
.setMaxSupply(1000)
.setSupplyKey(supplyKey)
.freezeWith(client);
//Sign the transaction with the token adminKey and the token treasury account private key
const signTx = await transaction.sign(treasuryKey);
//Sign the transaction with the client operator private key and submit to a Hedera network
const txRes = await signTx.execute(client);
print("txResponse", txRes);
const receipt = await txRes.getReceipt(client);
print("recepit", receipt);
const txRec = await txRes.getRecord(client);
print("txRecord", txRec);
//Get the token ID
let tokenId = receipt.tokenId;
//Log the token ID
console.log(`- Created NFT with Token ID: ${tokenId} \n`);
}
async function mintToken() {
// Mint new NFT
let mintTx = await new TokenMintTransaction()
.setTokenId(tokenId)
.setMetadata([
Buffer.from(
"A METADATA LINK"
),
])
.freezeWith(client);
//Sign the transaction with the supply key
let mintTxSign = await mintTx.sign(supplyKey);
print("Singed Tx", mintTxSign);
//Submit the transaction to a Hedera network
let minttxRes = await mintTxSign.execute(client);
print("Tx Response", minttxRes);
//Get the transaction receipt
let mintRx = await minttxRes.getReceipt(client);
print("Tx Receipt", mintRx);
//Get the transaction record
let mintRec = await minttxRes.getRecord(client);
print("Tx Record", mintRec);
//Log the serial number
console.log(
`- Created NFT ${tokenId} with serial: ${mintRx.serials[0].low} \n`
);
}
async function associateToken(tokenIds) {
//Create the associate transaction and sign with Alice's key
let tx = await new TokenAssociateTransaction()
.setAccountId(aliceId)
.setTokenIds(tokenIds)
.freezeWith(client)
.sign(aliceKey);
//Submit the transaction to a Hedera network
let txRes = await tx.execute(client);
print("Tx Response", txRes);
//Get the transaction receipt
let txRx = await txRes.getReceipt(client);
print("Tx Receipt", txRx);
//Get the transaction record
let txRec = await txRes.getRecord(client);
print("Tx Record", txRec);
//Confirm the transaction was successful
console.log(`- NFT association with Alice's account: ${txRx.status}\n`);
}
async function dissociateToken(tokenIds) {
//Create the associate transaction and sign with Alice's key
let tx = await new TokenDissociateTransaction()
.setAccountId(operatorAccountId)
.setTokenIds(tokenIds)
.freezeWith(client)
.sign(aliceKey);
//Submit the transaction to a Hedera network
let txRes = await tx.execute(client);
print("Tx Response", txRes);
//Get the transaction receipt
let txRx = await txRes.getReceipt(client);
print("Tx Receipt", txRx);
//Get the transaction record
let txRec = await txRes.getRecord(client);
print("Tx Record", txRec);
//Confirm the transaction was successful
console.log(`- NFT association with Alice's account: ${txRx.status}\n`);
}
async function transferToken() {
// Check the balance before the transfer for the treasury account
var balanceCheckTx = await new AccountBalanceQuery()
.setAccountId(treasuryId)
.execute(client);
console.log(
`- Treasury balance: ${balanceCheckTx.tokens._map.get(
tokenId.toString()
)} NFTs of ID ${tokenId}`
);
// Check the balance before the transfer for Alice's account
var balanceCheckTx = await new AccountBalanceQuery()
.setAccountId(aliceId)
.execute(client);
console.log(
`- Alice's balance: ${balanceCheckTx.tokens._map.get(
tokenId.toString()
)} NFTs of ID ${tokenId}`
);
// Transfer the NFT from treasury to Alice
// Sign with the treasury key to authorize the transfer
let tokenTransferTx = await new TransferTransaction()
.addNftTransfer(tokenId, 2 /*SN*/, treasuryId, aliceId)
.freezeWith(client)
.sign(treasuryKey);
let tokenTransferSubmit = await tokenTransferTx.execute(client);
print("Tx Response", tokenTransferSubmit);
let tokenTransferRx = await tokenTransferSubmit.getReceipt(client);
print("Tx Receipt", tokenTransferRx);
let tokenTransferRec = await tokenTransferSubmit.getRecord(client);
print("Tx Record", tokenTransferRec);
console.log(
`\n- NFT transfer from Treasury to Alice: ${tokenTransferRx.status} \n`
);
// Check the balance of the treasury account after the transfer
var balanceCheckTx = await new AccountBalanceQuery()
.setAccountId(treasuryId)
.execute(client);
console.log(
`- Treasury balance: ${balanceCheckTx.tokens._map.get(
tokenId.toString()
)} NFTs of ID ${tokenId}`
);
// Check the balance of Alice's account after the transfer
var balanceCheckTx = await new AccountBalanceQuery()
.setAccountId(aliceId)
.execute(client);
console.log(
`- Alice's balance: ${balanceCheckTx.tokens._map.get(
tokenId.toString()
)} NFTs of ID ${tokenId}`
);
}
// Hedera is an asynchronous environment :)
(async function () {
await printBalance("Operator", operatorAccountId);
try {
// await printBalance("Treasury", treasuryId);
// await createAccount();
// await generateKey();
// await createToken();
// await mintToken();
// await associateToken();
// await dissociateToken();
// await transferToken();
// await queryContract();
// await writeContract();
// await printBalance("Treasury", treasuryId);
} catch (err) {
console.error(err);
}
await printBalance("Operator", operatorAccountId);
process.exit();
})();

Some contract functions runs on hardhat network While others don't

I Got following error while testing my contract
$ npx hardhat test
NftyplayLicense
buyLicense
done!
1) should buy the license successfully
0 passing (2s)
1 failing
1) NftyplayLicense
buyLicense
should buy the license successfully:
Error: invalid address or ENS name (argument="name", value=undefined, code=INVALID_ARGUMENT, version=contracts/5.7.0)
at Logger.makeError (node_modules/#ethersproject/logger/src.ts/index.ts:269:28)
at Logger.throwError (node_modules/#ethersproject/logger/src.ts/index.ts:281:20)
at Logger.throwArgumentError (node_modules/#ethersproject/logger/src.ts/index.ts:285:21)
at /home/bhavesh/Documents/boilerplate/node_modules/#ethersproject/contracts/src.ts/index.ts:123:16
at step (node_modules/#ethersproject/contracts/lib/index.js:48:23)
at Object.next (node_modules/#ethersproject/contracts/lib/index.js:29:53)
at fulfilled (node_modules/#ethersproject/contracts/lib/index.js:20:58)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
Following is the Test that I have written
const { assert, expect } = require("chai")
const { network, ethers, deployments } = require("hardhat")
const { developmentChains } = require("../helper-hardhat-config")
!developmentChains.includes(network.name)
? describe.skip()
: describe("NftyplayLicense", function () {
let nftyplayLicenseContract, nftyPlayLicense, deployer, player, param
beforeEach(async function () {
const accounts = await ethers.getSigners()
deployer = accounts[0]
player = accounts[1]
await deployments.fixture(["all"])
nftyplayLicenseContract = await ethers.getContract("NftyPlayLicensing")
nftyPlayLicense = nftyplayLicenseContract.connect(deployer)
param = {
name: "NftyPlayLicensing",
category: "1",
durationInDays: "1",
licenseType: "1",
nftAddress: "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC",
nonce: 735,
price: "1000000000000000000",
r: "0xb07df588e0674bc28050a58a7f2cfd315f7e0aec136d0ebcf89fdcd9fa8aa928",
s: "0x109a8b6ff70709d2fecdba8b385097f2f979738518e4c444d4cf95b7e2c9621b",
signer: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
tokenId: "1",
v: 27,
}
})
describe("buyLicense", function () {
it("should buy the license successfully", async function () {
nftyPlayLicense.whitelist("0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC")
console.log("done!")
nftyPlayLicense = nftyplayLicenseContract.connect(player)
await expect(
nftyPlayLicense.buyLicense(param, "https://uri.com", {
value: ethers.utils.parseEther("1"),
})
).to.emit("NftyPlayLicensing", "LicenseBought")
const result = await nftyPlayLicense.getExecutedOrder(735)
assert.equal(result, true)
})
})
})
Note that
nftyPlayLicense.whitelist("0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC")
is running fine, not not in case of
nftyPlayLicense.buyLicense(param, "https://uri.com", {
value: ethers.utils.parseEther("1"),
})
I've made order and signature object by metamask and stored it locally and then using that i am calling buyLicense function from contract using that object as params.
this is my contract function:
function buyLicense(OrderTypes.LicenseOrder calldata order, string memory uri) public payable {
require(isOrderExecuted[order.nonce] == false, "Order is already Executed");
require(isCancelled[order.signer][order.nonce] == false, "Listing is Cancelled");
bytes32 orderHash = SignatureVerifier.hashMakerOrder(order, ORDER_TYPE_HASH);
validateMakerOrder(order, orderHash);
uint256 licenseTokenId = mintLicenseToken(msg.sender, uri, order);
isOrderExecuted[order.nonce] = true;
emit LicenseBought(
licenseTokenId,
order.price,
order.category,
order.tokenId,
order.signer,
order.licenseType,
order.nftContract
);
}
But I am unable to run that function

Getting a Runtime error when passing an Integer into a Solidity function that take uint256 as parameter

My Solidity smart contract has this function:
function getPlayerAddress(uint256 index) public view returns(address) {
return s_players[index];
}
And I am trying to pass an Integer as parameter via my frontend React application.
This is what the State looks like:
const [playerIndex, setPlayerIndex] = useState(0)
This is the function where I am trying to pass the value:
const updatePlayer = async () => {
const provider = new ethers.providers.Web3Provider(window.ethereum)
const contract = new ethers.Contract(stallionRunAddress, abi, provider)
**const newPlayer = await contract.getPlayerAddress(playerIndex)**
const newPlayerLevelBI = await contract.ownedHorseLevel(newPlayer)
const newPlayerLevel = parseInt(newPlayerLevelBI)
const newPlayerHorseArr = await contract.ownedHorseName(newPlayer)
const newPlayerHorse = newPlayerHorseArr[0].toString()
setPlayers(...players, {address: newPlayer, level: newPlayerLevel, horse: newPlayerHorse})
}
I get this error:
Unhandled Runtime Error
Error: call revert exception; VM Exception while processing transaction: reverted with panic code 50 [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method="getPlayerAddress(uint256)", data="0x4e487b710000000000000000000000000000000000000000000000000000000000000032", errorArgs=[{"type":"BigNumber","hex":"0x32"}], errorName="Panic", errorSignature="Panic(uint256)", reason=null, code=CALL_EXCEPTION, version=abi/5.7.0)
I have tried passing it as a value with 18 decimals (wei format):
playerIndex * 1e18
But it still doesn't fix the error. How do i fix this?
Solidity uint256 integers can be passed by web3js should be BigNumber instead of js integers. Also you can use string as well.

Error during minting with code from Opensea guide

I'm trying to deploy my first SmartContract following the Opensea guide. Everything was working fine until I set a price for my tokens and added the payable keyword. Now when I try to mint, I get the error Transaction value did not equal the mint price. Looking at the code I'm thinking I need to send ETH in the mint request in msg.value somehow but I'm not sure what the syntax would be for that?
Here's how I'm minting in shell:
npx hardhat mint --address {wallet_address}
Here's the mint function in JS:
task("mint", "Mints from the NFT contract")
.addParam("address", "The address to receive a token")
.setAction(async function (taskArguments, hre) {
const contract = await getContract("NFT", hre);
const transactionResponse = await contract.mintTo(taskArguments.address, {
gasLimit: 500_000,
});
console.log(`Transaction Hash: ${transactionResponse.hash}`);
});
And the mintTo function in the .sol contract:
// Main minting function
function mintTo(address recipient) public payable returns (uint256) {
uint256 tokenId = currentTokenId.current();
require(tokenId < TOTAL_SUPPLY, "Max supply reached");
require(msg.value == MINT_PRICE, "Transaction value did not equal the mint price");
currentTokenId.increment();
uint256 newItemId = currentTokenId.current();
_safeMint(recipient, newItemId);
return newItemId;
}
I figured out a solution for this issue. You need to set the price inside the mint task in mint.js like so:
task("mint", "Mints from the NFT contract")
.addParam("address", "The address to receive a token")
.setAction(async function (taskArguments, hre) {
const contract = await getContract("NFT", hre);
const transactionResponse = await contract.mintTo(taskArguments.address, {
gasLimit: 500_000,
value: ethers.utils.parseEther("0.01")
});
console.log(`Transaction Hash: ${transactionResponse.hash}`);
});
I have not figured out a way to have this import the MINT_PRICE variable from the contract. Note: You may need to add const { ethers } = require("ethers"); at the top of the file.

Error: invalid address (argument="address", value=undefined, code=INVALID_ARGUMENT, version=address/5.1.0)

I'm Getting this error when trying to deploy a smart contract with a function:
Error: invalid address (argument="address", value=undefined, code=INVALID_ARGUMENT, version=address/5.1.0) (argument="tokenAddress", value=undefined, code=INVALID_ARGUMENT, version=abi/5.0.7)
Here is my code:
const handlePresale = async (e) => {
e.preventDefault();
const web3 = await getWeb3();
const abiData = SafeHubPresaleAbi;
const contractAddress = "0x4498F943E0a13D70B28e7565CF4E33bF443e6Bf9";
const duration = {
seconds: function (val) {
return val;
},
minutes: function (val) {
return val * this.seconds(60);
},
hours: function (val) {
return val * this.minutes(60);
},
days: function (val) {
return val * this.hours(24);
},
weeks: function (val) {
return val * this.days(7);
},
years: function (val) {
return val * this.days(365);
},
};
const latestTime = new Date().getTime();
const openingTime = latestTime + duration.minutes(1);
const closingTime = openingTime + duration.minutes(10);
const liqAddingTime = closingTime + duration.minutes(5);
let _info = {
address : "0x4498F943E0a13D70B28e7565CF4E33bF443e6Bf9",
tokenPrice : web3.utils.toWei("10", "ether"),
hardCap: web3.utils.toWei("100", "ether"),
softCap: web3.utils.toWei("30", "ether"),
minInv: web3.utils.toWei("0.1", "ether"),
maxInv: web3.utils.toWei("5", "ether"),
openingTime: openingTime,
closingTime: closingTime,
};
let _uniInfo = {
listingPrice: web3.utils.toWei("20", "ether"),
liqTime: liqAddingTime,
lockTime: 365,
precentLock: 25,
};
let _stringInfo = {
listingName: "WER sale",
};
const preslaeContract = await new web3.eth.Contract(
abiData,
contractAddress
);
// console.log(preslaeContract.methods)
preslaeContract.methods
.createPresale(_info,_uniInfo,_stringInfo)
.call((err, result) => {
console.log(result), console.log(err);
});
}
Solidity constructor:
constructor(address _safuFactoryAddress, address _safuDevAddress) public {
require(_safuFactoryAddress != address(0));
require(_safuDevAddress != address(0));
safuFactoryAddress = payable(_safuFactoryAddress);
safuDevAddress = payable(_safuDevAddress);
}
since there are still no answers yet, but over 1k views though, I'll leave here a solution if anyone else is facing the same error.
The solidity constructor in your example expects 2 arguments of type address. This means if you deploy your contract you also need to provide those 2.
As for the deployment:
No matter how you deploy your contract, providing all constructor arguments should solve your problem and your contract should be able to get deployed now.
If you work with truffle, you need to adjust your deployer .../migrations/2_deploy_contracts.js and pass 2 addresses to satisfy the constructor parameters.
var SafeHubPresale = artifacts.require("./SafeHubPresale.sol");
module.exports = function(deployer) {
deployer.deploy(SafeHubPresale, [address1], [address2]);
};
The same applies for test:
let's say:
var myContract = await SafeHubPresale.new(accounts[1], accounts[2], {from: accounts[0], gas: 0});
For those in Remix, select the drop down next to "deploy" and you will need to provide a "to" & "from" address for this to work
In your smart contract, more than one argument may present and cannot fulfill its value when you deploy. When you deploy you take these values and call deploy() it's working correctly.
In your constructor
constructor(address _safuFactoryAddress, address _safuDevAddress)
more than one address value present there you may not provide this value when you deploy.