How to deposit ether to an account using solidity and web3? - blockchain

I am building a sample smart contract . I am trying to deposit ether from 1 account to another but the issue is amount is deducted from the sender's account but not able to deposit to receiver's account.
Here is my contract code :
pragma solidity ^0.5.0;
contract ApprovalContract{
address public sender;
address public receiver;
function deposit(address _receiver) external payable {
require(msg.value > 0);
sender = msg.sender;
receiver = _receiver;
address payable _rec = receiver.make_payable();
_rec.transfer(address(this).balance);
}
using address_make_payable for address;
}
library address_make_payable {
function make_payable(address x) internal pure returns (address payable) {
return address(uint160(x));
}
}
Here is my web3 code :
let ApprovalContract = new web3.eth.Contract(
abi,
"0xABd4495e3afc9E61Bbbf54620587aB4B48CEd7d3" //contract address
);
ApprovalContract.methods
.deposit("0xF33ca58CbD25bC0fFe5546Dc494E5c61C8D7fFc3")
.send(
{
from: "0x7186ffcf5ea764257fdbaefccb9472f054495d11",
gas: 100000,
value: web3.utils.toWei("1", "ether")
},
(err, res) =>
err
? console.log(`error: ${err}`)
: console.log(`Success: ${res}`)
);

Just add some mapping in your smart contract, like this mapping( address => uint256 ) balance and this is fixed smart contract for you :
pragma solidity ^0.5.0;
contract ApprovalContract{
address payable owner = msg.sender;
mapping(address => uint256) balance;
function deposit() external payable {
require(msg.value > 0);
sender = msg.sender;
deposited = msg.value;
receiver = owner;
balance[sender] = deposited;
receiver.transfer(deposited);
}
}

Related

solidity transaction error, The called function should be payable

I want to write a contract using router from uniswap. But when swapping 1 token to another, I get an error
The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.
I attach the code from below. How can I fix the error ?
// SPDX-License-Identifier: MIT
pragma solidity =0.8.7;
pragma abicoder v2;
import "https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/interfaces/ISwapRouter.sol";
import "https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/interfaces/IQuoter.sol";
interface IUniswapRouter is ISwapRouter {
function refundETH() external payable;
}
contract SwapV1 {
IUniswapRouter public constant uniswapRouter = IUniswapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564);
IQuoter public constant quoter = IQuoter(0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6);
address public token1;
uint24 public ownerFee;
function setToken1(address _token1) payable external {
token1 = _token1;
}
function setFee(uint24 _fee) payable external {
ownerFee = _fee;
}
function convertToken1ToToken2(address token2) external payable {
require(msg.value > 0, "Must pass non 0 ETH amount");
uint256 deadline = block.timestamp + 20; // using 'now' for convenience, for mainnet pass deadline from frontend!
address tokenIn = token1;
address tokenOut = token2;
uint24 fee = ownerFee;
address recipient = msg.sender;
uint256 amountIn = msg.value;
uint256 amountOutMinimum = 1;
uint160 sqrtPriceLimitX96 = 0;
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams(
tokenIn,
tokenOut,
fee,
recipient,
deadline,
amountIn,
amountOutMinimum,
sqrtPriceLimitX96
);
uniswapRouter.exactInputSingle{ value: msg.value }(params);
uniswapRouter.refundETH();
// refund leftover ETH to user
(bool success,) = msg.sender.call{ value: address(this).balance }("");
require(success, "refund failed");
}
function convertToken1ToExactToken2(uint256 token2Amount, address token2) external payable {
require(token2Amount > 0, "Must pass non 0 DAI amount");
require(msg.value > 0, "Must pass non 0 ETH amount");
uint256 deadline = block.timestamp + 20; // using 'now' for convenience, for mainnet pass deadline from frontend!
address tokenIn = token1;
address tokenOut = token2;
uint24 fee = ownerFee;
address recipient = msg.sender;
uint256 amountOut = token2Amount;
uint256 amountInMaximum = msg.value;
uint160 sqrtPriceLimitX96 = 0;
ISwapRouter.ExactOutputSingleParams memory params = ISwapRouter.ExactOutputSingleParams(
tokenIn,
tokenOut,
fee,
recipient,
deadline,
amountOut,
amountInMaximum,
sqrtPriceLimitX96
);
uniswapRouter.exactOutputSingle{ value: msg.value }(params);
uniswapRouter.refundETH();
// refund leftover ETH to user
(bool success,) = msg.sender.call{ value: address(this).balance }("");
require(success, "refund failed");
}
// do not used on-chain, gas inefficient!
function getEstimatedToken1forToken2(uint token2Amount, address token2) external payable returns (uint256) {
address tokenIn = token1;
address tokenOut = token2;
uint24 fee = ownerFee;
uint160 sqrtPriceLimitX96 = 0;
return quoter.quoteExactOutputSingle(
tokenIn,
tokenOut,
fee,
token2Amount,
sqrtPriceLimitX96
);
}
// important to receive ETH
receive() payable external {}
}

Sending eth from one metamask wallet to another wallet in solidity

I'm trying to write a smart contract to transfer eth from one metamask wallet to another metamask wallet in solidity in remix with Injected Web 3 environment. I deployed the contract but the transaction send_ETH failed. Could anyone help me figure out why? Thank you so much
pragma solidity >=0.8.0;
// Get the latest ETH/USD price from chainlink price feed
import "#chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract myContract {
address payable[] recipients;
mapping(address => uint256) public balanceAccount;
address public owner;
constructor() {
owner = msg.sender;
}
function send_ETH(address payable recipient, uint256 amount) public {
//set the minimum amount of dollar to transfer
uint256 minimumUSD = 0.01 * 10 ** 18;
amount = minimumUSD;
require(getConversionRate(amount) >= minimumUSD, "You need to spend more ETH!");
this.invest(amount);
this.fund(recipient);
}
function invest(uint256 amount) payable external{
//transfer amount ETH from metadata wallet to smart contract
recordTransaction(address(this), amount, false);
recordTransaction(owner, amount, true);
address payable contractAddress = payable(address(this));
contractAddress.send(amount);
}
function fund(address payable recipient) external {
//transfer amount ETH from this smart contract to the recipient
recordTransaction(address(this), address(this).balance, true);
recordTransaction(recipient, address(this).balance, false);
recipient.send(address(this).balance);
}
function recordTransaction(address recipient, uint256 deposit, bool out) private {
if (out) {
balanceAccount[recipient] -= deposit;
} else {
balanceAccount[recipient] += deposit;
}
}
function getVersion() public view returns (uint256){
AggregatorV3Interface priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
return priceFeed.version();
}
function getPrice() public view returns(uint256){
AggregatorV3Interface priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
(,int256 answer,,,) = priceFeed.latestRoundData();
// ETH/USD rate in 18 digit
return uint256(answer * 10000000000);
}
function getConversionRate(uint256 ethAmount) public view returns (uint256){
uint256 ethPrice = getPrice();
uint256 ethAmountInUsd = (ethPrice * ethAmount) / 1000000000000000000;
// the actual ETH/USD conversation rate, after adjusting the extra 0s.
return ethAmountInUsd;
}
}
your function invest() is wrong
function invest(uint256 amount) payable external{
//transfer amount ETH from metadata wallet to smart contract
recordTransaction(address(this), amount, false);
recordTransaction(owner, amount, true);
//these 2 lines below are wrong
address payable contractAddress = payable(address(this));
contractAddress.send(amount);
}
You marked that function as payable, that's correct if you interact directly with that, but you interact with send_eth, so it needs to be payable to receive eth
Then you saved the contract address as payable and did contractAddress.send(amount) that's mean: "contract send 'amount' to contract"
the send() function send money from contract to an address
also the amount var is wrong
all eth sent are sent directly through tx information, and not through data
the function correct:
function send_ETH(address payable recipient) payable public {
//set the minimum amount of dollar to transfer
uint256 minimumUSD = 0.01 * 1e18;
require(getConversionRate(msg.value) >= minimumUSD, "You need to spend more ETH!");
this.invest(msg.value);
this.fund(recipient);
}
function invest() internal{
//transfer amount ETH from metadata wallet to smart contract
recordTransaction(address(this), amount, false);
recordTransaction(owner, amount, true);
}
then when calling send_eth you have to write manually the amount of eth to send, if you will make an interface for that, you can write the eth amount to send inside the tx details like:
const transaction = {
'to': '0x31B98D14007bDEe637298086988A0bBd31184523', //contract address
'value': 1, //1 eth
'gas': 30000,
'maxFeePerGas': 1000000108,
'nonce': nonce,
};

ERC721 Minted NFT not showing on Opensea.io testnet

I run my code on rinkeby etherscan network and it works perfectly. But the image and descriptions are not showing on opensea testnet. I run the /validate/ url it shows Valid: "false".
Here is what I found when I force update on opensea, https://testnets-api.opensea.io/api/v1/asset/0x668D179B933af761e4732B084290D32B3235C22b/0/?force_update=true
Here is my code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
import "#openzeppelin/contracts/utils/Counters.sol";
import "./ERC2981ContractWideRoyalties.sol";
import "hardhat/console.sol";
contract SmoothApe is ERC721URIStorage, Ownable, ERC2981ContractWideRoyalties {
using Counters for Counters.Counter;
using Strings for uint256;
Counters.Counter private _tokenIdCounter;
event EmitNFT(address sender, uint256 tokenId);
uint256 public preSaleTokenPrice = 0.01 ether;
uint256 public costPrice = 0.02 ether;
uint256 public maxSupply = 10000;
uint256 public maxMintNft = 10;
string public baseURI;
string public baseExtension = ".json";
string public notRevealedUri;
bool public paused = false;
bool public revealed = true;
bool public presale = false;
// set 0x7350243981aB92E2A3646e377EBbFC28e9DE96C1 as payable admn wallet
address payable public adminWallet = payable(0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2);
address payable public communityWallet = payable(0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db);
address payable public t1Wallet = payable(0x78731D3Ca6b7E34aC0F824c42a7cC18A495cabaB);
address payable public t2Wallet = payable(0x617F2E2fD72FD9D5503197092aC168c91465E7f2);
address payable public t3Wallet = payable(0x17F6AD8Ef982297579C203069C1DbfFE4348c372);
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
constructor(string memory _name, string memory _symbol,string memory _initBaseURI, string memory _initNotRevealedUri) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedUri(_initNotRevealedUri);
}
// inherit and override erc165
function supportsInterface(bytes4 interfaceId) public view virtual override (ERC721, ERC2981Base) returns (bool) {
return super.supportsInterface(interfaceId);
}
// set Royalty value (between 0 and 10000)
function setRoyalties(address recipient, uint256 value) public onlyOwner {
_setRoyalties(recipient, value);
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function mintApe() public payable {
uint256 tokenId = _tokenIdCounter.current();
require(!paused, "Minting is paused");
require(msg.sender != owner(), "You can't mint ape to admin");
// require(_mintAmount > 0, "Mint amount must be greater than 0");
// require(_mintAmount <= maxSupply, "Mint amount must be less than or equal to max supply");
if(presale == true) {
preSaleTokenPrice = costPrice;
}
require(msg.value >= costPrice, string(abi.encodePacked("Must send at least ", costPrice.toString(), " ether to purchase")));
require(balanceOf(msg.sender) < maxMintNft, "You can only own 11 ape at a time");
// require(_mintAmount + balanceOf(msg.sender) <= maxMintNft, "You can only own 10 ape at a time");
// adminWallet.transfer(msg.value);
payable(owner()).transfer(msg.value);
emit EmitNFT(msg.sender, tokenId);
// for(uint256 i = 1; i <= _mintAmount; i++){
_safeMint(msg.sender, tokenId);
// _setTokenURI(tokenId, _baseURI());
_tokenIdCounter.increment();
// }
}
// admin mint ape to wallet
function mintApeTo(address _to, uint256 _mintAmount) public onlyOwner {
require(!paused, "Minting is paused");
require(_mintAmount > 0, "Mint amount must be greater than 0");
require(_mintAmount <= maxSupply, "Mint amount must be less than or equal to max supply");
for(uint256 i = 1; i <= _mintAmount; i++){
uint256 tokenId = _tokenIdCounter.current();
_safeMint(_to, tokenId);
// _setTokenURI(tokenId, _baseURI());
_tokenIdCounter.increment();
}
}
function getCostPrice() public view virtual returns (uint256) {
return costPrice;
}
// function to set cost of ape
function setCost(uint256 _preSaleTokenPrice, uint256 _publicTokenPrice) public onlyOwner {
preSaleTokenPrice = _preSaleTokenPrice;
costPrice = _publicTokenPrice;
}
// set presale to true
function setPresale(bool _presale) public onlyOwner {
presale = _presale;
}
function reveal(bool _reveal) public onlyOwner {
revealed = _reveal;
}
// pause function
function pause() public onlyOwner {
paused = true;
}
// set function for setBaseURI and setNotRevealed function
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwner {
_setTokenURI(_tokenId, _tokenURI);
}
// override tokenURI function
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
require(tokenId < _tokenIdCounter.current(), "Token ID must be less than the total supply");
if(!revealed) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
baseExtension))
: "";
}
}
Here is a sample of NFT i mint:
https://testnets.opensea.io/assets/0x668D179B933af761e4732B084290D32B3235C22b/0
my ipfs CID:
ipfs://QmaoMZ19zhpC6T4id6jdBP1Qz5dQSmRZMkQZU7Zt8hyFNQ/
as you can see in the right up corner there is a "reload" button, you need to click it to reload the ipfs on opensea
I had the same problem. Turned out that I wasn't uploading the images to ipfs correctly because it was visible only to me on my machine. So try to see if the ipfs metadata are correctly formated and are accesible from different devices.
Also you shouldn't just paste your entire contract in. Tt is really hard to answer your question then. Just write out the important sections of the code.

How to transfer ERC1155 token using web3js?

I am trying to transfer ERC1155 tokens to another account. I have deployed the contract and have put down my contract code below.
The problem I am facing is I get the below error when I call getMyToken function from my frontend web3js code.
{code: -32603, message: 'execution reverted: ERC1155: caller is not owner nor approved', data: {…}}
Not sure what is happening. I am calling the function as below from frontend. The isApproved function is returning true.
const selectedAccountIsApproved = await monkeysContract.methods.isApproved(selectedAccount).call();
console.log('IS APPROVED RESULT: ', selectedAccountIsApproved);
if(selectedAccountIsApproved) {
const result = await monkeysContract.methods.mintMyMonkey(selectedAccount, 0).call();
console.log('Transfer Result: ', result);
} else {
console.log('Account not approved by owner for transfers');
}
NOTE:
I have called the setApprovalForAll method and approved the receiver account.
I am able to call isApprovedForAll and verify that the account is approved.
I am able to transfer tokens to the receiver through Etherscan contract interface.
Contract Code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "#openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
contract Monkeys is ERC1155, Ownable {
uint256 public constant CC1 = 0;
uint256 public constant CC2 = 1;
mapping (uint256 => string) private _uris;
constructor() public ERC1155("https://game.example/api/item/{id}.json") {
_mint(msg.sender, CC1, 1000, "");
_mint(msg.sender, CC2, 1000, "");
}
function uri(uint256 tokenId) override public view returns (string memory) {
return(_uris[tokenId]);
}
function setTokenUri(uint256 id, string memory url) public onlyOwner {
require(bytes(_uris[id]).length == 0, "Cannot set uri twice");
_uris[id] = url;
}
function transfer(address from, address to, uint256 id, uint256 amount, bytes memory data) public {
safeTransferFrom(from, to, id, amount, data);
}
function isApproved(address user) public view virtual returns (bool) {
return isApprovedForAll(owner(), user);
}
function getMyToken(address to, uint256 id) public {
transfer(owner(), to, id, 1, 'test');
}
}

"VM Exception while processing transaction: revert", when running a chainlink node and try to deploy TestnetConsumer contract?

The scenario is when deploying a ATestnetConsumer.sol on mathchain via Remix, following the official tutorial to run a node on mathchain, which is a EVM-compatitable public chain. And I finish deploying the Oracle contract and LINKToken contract, and running the node on mathchain successfully, but when trying to deploy a TestnetConsumer contract, it shows that:
Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
Internal JSON-RPC error. { "code": -32603, "message": "VM Exception while processing transaction: revert", "data": "" }
Anybody know why?
The TestnetConsumer contract is list as below:
pragma solidity 0.4.24;
import "https://github.com/smartcontractkit/chainlink/evm-contracts/src/v0.4/ChainlinkClient.sol";
import "https://github.com/smartcontractkit/chainlink/evm-contracts/src/v0.4/vendor/Ownable.sol";
contract ATestnetConsumer is ChainlinkClient, Ownable {
uint256 constant private ORACLE_PAYMENT = 1 * LINK;
uint256 public currentPrice;
int256 public changeDay;
bytes32 public lastMarket;
event RequestEthereumPriceFulfilled(
bytes32 indexed requestId,
uint256 indexed price
);
event RequestEthereumChangeFulfilled(
bytes32 indexed requestId,
int256 indexed change
);
event RequestEthereumLastMarket(
bytes32 indexed requestId,
bytes32 indexed market
);
constructor() public Ownable() {
setPublicChainlinkToken();
}
function requestEthereumPrice(address _oracle, string _jobId)
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(_jobId), this, this.fulfillEthereumPrice.selector);
req.add("get", "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD");
req.add("path", "USD");
req.addInt("times", 100);
sendChainlinkRequestTo(_oracle, req, ORACLE_PAYMENT);
}
function requestEthereumChange(address _oracle, string _jobId)
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(_jobId), this, this.fulfillEthereumChange.selector);
req.add("get", "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD");
req.add("path", "RAW.ETH.USD.CHANGEPCTDAY");
req.addInt("times", 1000000000);
sendChainlinkRequestTo(_oracle, req, ORACLE_PAYMENT);
}
function requestEthereumLastMarket(address _oracle, string _jobId)
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(_jobId), this, this.fulfillEthereumLastMarket.selector);
req.add("get", "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD");
string[] memory path = new string[](4);
path[0] = "RAW";
path[1] = "ETH";
path[2] = "USD";
path[3] = "LASTMARKET";
req.addStringArray("path", path);
sendChainlinkRequestTo(_oracle, req, ORACLE_PAYMENT);
}
function fulfillEthereumPrice(bytes32 _requestId, uint256 _price)
public
recordChainlinkFulfillment(_requestId)
{
emit RequestEthereumPriceFulfilled(_requestId, _price);
currentPrice = _price;
}
function fulfillEthereumChange(bytes32 _requestId, int256 _change)
public
recordChainlinkFulfillment(_requestId)
{
emit RequestEthereumChangeFulfilled(_requestId, _change);
changeDay = _change;
}
function fulfillEthereumLastMarket(bytes32 _requestId, bytes32 _market)
public
recordChainlinkFulfillment(_requestId)
{
emit RequestEthereumLastMarket(_requestId, _market);
lastMarket = _market;
}
function getChainlinkToken() public view returns (address) {
return chainlinkTokenAddress();
}
function withdrawLink() public onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer");
}
function cancelRequest(
bytes32 _requestId,
uint256 _payment,
bytes4 _callbackFunctionId,
uint256 _expiration
)
public
onlyOwner
{
cancelChainlinkRequest(_requestId, _payment, _callbackFunctionId, _expiration);
}
function stringToBytes32(string memory source) private pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly { // solhint-disable-line no-inline-assembly
result := mload(add(source, 32))
}
}
}
The problem is located at the constructor:
constructor() public Ownable() {
setPublicChainlinkToken();
}
When you run a node on a public-chain, and deploy a totally new LINKToken contract as the way to transferAndCall the service provided by your own node, do remember to replace the line: setPublicChainlinkToken() to:
// set the Oracle contract address
setChainlinkOracle(YOUR_ORACLE_CONTRACT_ADDRESS);
// set LINKToken contract address
setChainlinkToken(YOUR_LINKTOKEN_CONTRACT_ADDRESS);
Then you should be good to go. And remember that you should deposit some LINK token before invoking the function to get service from your Chainlink node!