The called function should be payable if you send value and the value you send should be less than your current balance - solidity

When I call changeScore, I get an error
[enter image description here][1]
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.
Code
pragma solidity ^0.8.0;
// Student
contract Score{
address public teacher;
mapping (address => uint) StudentScore;
modifier onlyTeacher(){
require(msg.sender == teacher,"Don't Change Score");
_;
}
function addTeacher(address _address) public{
teacher = _address;
}
// external
function IScore(address _account,uint _score) public onlyTeacher{
require(_score <= 100,"Score more then 100");
StudentScore[_account] = _score;
}
function getStudentScore(address _address) public view returns (uint){
return StudentScore[_address];
}
}
interface IScoreService{
function IScore(address _account, uint _score) external;
}
// Teacher
contract Teacher{
address public selfAddress;
IScoreService public score;
constructor(){
selfAddress = address(this);
}
function changeScore(address _account, uint _score) public {
score.IScore(_account, _score);
}
}
[1]: https://i.stack.imgur.com/KwWHz.png

The IScore() function has a onlyTeacher modifier, effectively allowing the function to be executed only from the teacher address.
Mind that the address executing the function is the Teacher contract address in this case.
Solution: Set the Teacher contract address as the teacher variable by executing the addTeacher() function (passing it the Teacher contract address) on the Score contract. Then you'll be able to execute the IScore() function through the Teacher contract.

Related

I need help how to fix the "else if" = only owner is allowed to call the _action from the main contract. this is just the logger

I need help how to fix the "else if" = only owner is allowed to call the _action from the main contract. this is just the logger. below is the contract logger.
contract logger {
function log(address _caller, uint _amount, string memory _action) public {
if (equal(_action, "withdraw")) {
revert("It's a frank!");
else if (equal(_caller, "owner"));
assert();
}
}
function equal(string memory _a, string memory _b) public pure returns (bool) {
return keccak256(abi.encode(_a)) == keccak256(abi.encode(_b));
So I am guessing you want to call the function from the main contract in the logger contract. So we need to know the address of the main contract and the function signature of the action function in the main contract. Suppose the function signature of action function in the main contract is action(unit256). And let's initialize the main contract in the constructor.
So the contract logger would look like this:
// SPDX-License-Identifier: MIT
pragma solidity 0.8.15;
import "./MainContract.sol";
contract Logger {
address private owner;
MainContract mainContract;
constructor(address _mainContract){
owner = msg.sender;
mainContract = new MainContract(_mainContract);
}
function log(address _caller, uint _amount, string memory _action, uint256 value) public {
if (equal(_action, "withdraw")) {
// Do whatever you want
}
else if (_caller == owner){
mainContract.action(value);
// Do whatever you want
}
}
function equal(string memory _a, string memory _b) public pure returns (bool) {
return keccak256(abi.encode(_a)) == keccak256(abi.encode(_b));
}
}

solidity - Invalid type for argument in function call. Invalid implicit conversion from address to address payable requested

I am trying to give address as payable but I am getting error at msg.sender and address(_author).transfer(msg.value) . it was showing like Invalid type for argument in function call. Invalid implicit conversion from address to address payable requested. i tried many ways to solve every time i replace the same error. before adding payable to author it was fine, but when added payable to author then it started getting error. In both, msg.sender and msg.value
pragma solidity >=0.4.0 <0.9.0;
contract SocialNetwork {
string public name;
uint public postCount = 0;
mapping(uint => Post) public posts;
struct Post {
uint id;
string content;
uint tipAmount;
address payable author;
}
event PostCreated(
uint id,
string content,
uint tipAmount,
address payable author
);
event PostTipped(
uint id,
string content,
uint tipAmount,
address payable author
);
constructor() public {
name = "Yash university Social Network";
}
function createPost(string memory _content) public {
//REquire Valid content
require(bytes(_content).length > 0);
// InCREMENT the post count
postCount ++;
// Create the post
posts[postCount] = Post(postCount, _content, 0, msg.sender);
// Trigger event
emit PostCreated(postCount, _content, 0, msg.sender);
}
function tipPost(uint _id) public payable {
//fetch the post
Post memory _post = posts[_id];
//fetch the author
address payable _author = _post.author;
//pay the author
address(_author).transfer(msg.value);
//increment the tip post
_post.tipAmount = _post.tipAmount + msg.value;
//update the post
posts[_id] = _post;
//Trigger an event
emit PostTipped(postCount, _post.content, _post.tipAmount, _author);
}
}
You have a few issues in your code:
1- in the Post struct, you defined address as payable:
struct Post {
uint id;
string content;
uint tipAmount;
address payable author;
}
But when you are creating a post, you are passing msg.sender which has address type. Before v0.8.0 msg.sender was payable but since than you have to cast it as payable(msgs.sender). it should be:
function createPost(string memory _content) public {
require(bytes(_content).length > 0);
postCount ++;
posts[postCount] = Post(postCount, _content, 0, payable(msg.sender));
emit PostCreated(postCount, _content, 0, payable(msg.sender));
}
2- in tipPost function you are getting payable address
address payable _author = _post.author;
but then you are casting it with address. In solidity address and payable address are two different things. send and transfer are only available to the payable address type. You dont need this:
address(_author).transfer(msg.value);
instead just
_author.transfer(msg.value);

A Lottery Solidity Smart Contract Accept token as payment instead of ether

pragma solidity ^0.4.21;
contract Lottery {
address public manager;
address[] public players;
constructor() public {
manager = msg.sender;
}
function enter() public payable {
require(msg.value > .01 ether);
players.push(msg.sender);
}
function random() private view returns (uint) {
return uint(keccak256(abi.encodePacked(block.difficulty, now, players)));
}
function pickWinner() public restricted {
uint index = random() % players.length;
players[index].transfer(address(this).balance);
players = new address[](0);
}
function getPlayers() public view returns (address[]) {
return players;
}
modifier restricted() {
require(msg.sender == manager);
_;
}
}
I want o change the function
function enter() public payable {
require(msg.value > .01 ether);
players.push(msg.sender);
}
Instead of ether, user use our token/erc20 to enter the lottery
You can define an interface (in your contract) of the token contract. Since you're only going to be using the transferFrom() function, this is the only function that you need to define in the interface (no matter that the token contract contains other functions as well).
interface IERC20 {
function transferFrom(address _from, address _to, uint256 _amount) external returns (bool);
}
The you can execute the transferFrom() function of the token, passing it arguments:
from: the user executing your enter() function
to: your contract
amount: Assuming the token has 18 decimals (most tokens do), you can use the ether helper unit, because it effectively calculates "0.01 * 10^18 (or 10^16, or 10000000000000000) of the token smallest units", which is 0.01 of the token. Otherwise, you'll need to recalculate this number based on the token decimals.
function enter() public payable {
IERC20 token = IERC20(address(0x123)); // Insert the token contract address instead of `0x123`
require(token.transferFrom(msg.sender, address(this), .01 ether));
players.push(msg.sender);
}
Important: Mind that the user needs to approve() your contract to spend their tokens beforehand (from their address), otherwise the token transfer would fail. There's a security reason for that, read more about it in the bottom part of this answer.

How to make an API call in solidity?

I have a smart contract that I’m trying to make, it pays out the winners of my League of Legends tournament. However I’m running into an issue. I need to make an API call to get the winner of the match, I have a simple URL that I’ve make.
"example-winner.com/winner"
And it returns simple JSON with the address of the winner:
{"winner":"0xa7D0......."}
However, I’m not sure how to make the API call to the outside function. I know I need to use some sort of oracle technology.
Any thoughts? Below is my code:
pragma solidity ^0.4.24;
contract LeagueWinners{
address public manager;
address[] public players;
uint256 MINIMUM = 1000000000000000;
constructor() public{
manager = msg.sender;
}
function enter() public payable{
assert(msg.value > MINIMUM);
players.push(msg.sender);
}
function getWinner() public{
assert(msg.sender == manager);
// TODO
// Get the winner from the API call
result = 0; // the result of the API call
players[result].transfer(address(this).balance);
// returns an adress object
// all units of transfer are in wei
players = new address[](0);
// this empties the dynamic array
}
}
You can use Chainlink as your Oracle.
As many have mentioned, you will need an oracle to get your API call. Something that is important to note, your contract is actually asking an oracle to make your API call for you, and not making the API call itself. This is because the blockchain is deterministic. For more information see this thread.
To answer your question, you can use the decentralized oracle service Chainlink.
You'd add a function:
function getWinner()
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
req.add("get", "example-winner.com/winner");
req.add("path", "winner");
sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
}
For the purpose of the following exmaple, we are going to pretend you want to return a uint256 instead of an address. You can return a bytes32 and then convert it to an address, but for simplicity let's say the API returns the index of the winner. You'll have to find a node and jobId that can make a http.get request and return a uint256 object. You can find nodes and jobs from market.link. Each testnet (Ropsten, Mainnet, Kovan, etc) has different node addresses, so make sure you pick the right ones.
For this demo, we are going to use LinkPool's ropsten node
address ORACLE=0x83F00b902cbf06E316C95F51cbEeD9D2572a349a;
bytes32 JOB= "c179a8180e034cf5a341488406c32827";
Ideally, you'd choose a number of nodes to run your job, to make it trustless and decentralized. You can read here for more information on precoordinators and aggregating data. disclosure I am the author of that blog
Your full contract would look like:
pragma solidity ^0.6.0;
import "github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol";
contract GetData is ChainlinkClient {
uint256 indexOfWinner;
address public manager;
address payable[] public players;
uint256 MINIMUM = 1000000000000000;
// The address of an oracle
address ORACLE=0x83F00b902cbf06E316C95F51cbEeD9D2572a349a;
//bytes32 JOB= "93fedd3377a54d8dac6b4ceadd78ac34";
bytes32 JOB= "c179a8180e034cf5a341488406c32827";
uint256 ORACLE_PAYMENT = 1 * LINK;
constructor() public {
setPublicChainlinkToken();
manager = msg.sender;
}
function getWinnerAddress()
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
req.add("get", "example-winner.com/winner");
req.add("path", "winner");
sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
}
// When the URL finishes, the response is routed to this function
function fulfill(bytes32 _requestId, uint256 _index)
public
recordChainlinkFulfillment(_requestId)
{
indexOfWinner = _index;
assert(msg.sender == manager);
players[indexOfWinner].transfer(address(this).balance);
players = new address payable[](0);
}
function enter() public payable{
assert(msg.value > MINIMUM);
players.push(msg.sender);
}
modifier onlyOwner() {
require(msg.sender == manager);
_;
}
// Allows the owner to withdraw their LINK on this contract
function withdrawLink() external onlyOwner() {
LinkTokenInterface _link = LinkTokenInterface(chainlinkTokenAddress());
require(_link.transfer(msg.sender, _link.balanceOf(address(this))), "Unable to transfer");
}
}
This would do about everything you need.
If you can't adjust the API to return a uint, you can return a bytes32 and then convert it to an address or a string.
function bytes32ToStr(bytes32 _bytes32) public pure returns (string memory) {
bytes memory bytesArray = new bytes(32);
for (uint256 i; i < 32; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
You cannot. The vm does not have any I/O outside of the blockchain itself. Instead you will need to tell your smart contract who the winner is and then the smart contract can just read the value of that variable.
This design pattern is also known as the "oracle". Google "Ethereum oracle" for more info.
Basically your web server can call your smart contract. Your smart contract cannot call your web server. If you need your smart contract to access a 3rd party service then your web server will need to make the request then forward the result to solidity by calling a function in your smart contract.
You didn't properly explain what you are trying to do. Are you having trouble with the solidity code? or rather with your server? Here is an edited version. See if it helps.
pragma solidity ^0.4.24;
contract LeagueWinners{
address public manager;
//address[] public players;
uint256 MINIMUM = 1000000000000000;
constructor() public{
manager = msg.sender;
}
struct Player {
address playerAddress;
uint score;
}
Player[] public players;
// i prefer passing arguments this way
function enter(uint value) public payable{
assert(msg.value > MINIMUM);
players.push(Player(msg.sender, value));
}
//call this to get the address of winner
function winningPlayer() public view
returns (address winner)
{
uint winningScore = 0;
for (uint p = 0; p < players.length; p++) {
if (players[p].score > winningScore) {
winningScore = players[p].score;
winner = players[p].playerAddress;
}
}
}
// call this to transfer fund
function getWinner() public{
require(msg.sender == manager, "Only a manager is allowed to perform this operation");
// TODO
address winner = winningPlayer();
// Get the winner from the API call
//uint result = 0; // the result of the API call
winner.transfer(address(this).balance);
// returns an adress object
// all units of transfer are in wei
delete players;
// this empties the dynamic array
}
}
At least that is what I understand by your question.

Transfer ownership web3

I am creating a dapp to transfer ownership of the contract from one address to another using testrpc. However,I keep encountering this problem. I have tried using sentransaction method to do perform this ownership change.Perhaps I'm calling the exchange in a wrong manner.
Solidity version 0.4.4
web3 "version": "0.20.2"
web3.js:3127 Uncaught Error: VM Exception while processing transaction: invalid opcode
at Object.InvalidResponse (web3.js:3127)
at RequestManager.send (web3.js:6332)
at Eth.send [as sendTransaction] (web3.js:5066)
at SolidityFunction.sendTransaction (web3.js:4122)
at SolidityFunction.execute (web3.js:4208)
at transferOwnership (luxcure_manu.html:309)
at HTMLButtonElement.onclick (luxcure_manu.html:378
Full solidity contract as of yet.
pragma solidity ^0.4.4;
// TODO: Hash of the cert through IPFS Hash
// Transfer ownership of smart contract
contract LuxSecure {
address public contract_owner; //Manufacturer/owner
//string public current_owner; //Current Owner of good
bytes32 public model; //Model
mapping(uint => address) public owners; //list of owners
uint256 public owners_count;
bytes32 public status; // (Public(Owned by no one), Private(Bought by another entity),stolen(Stolen from public or private))
bytes32 public date_manufactured; //Time
// Set manufacturer of the Good RUN ONCE ONLY
function manufacturer() public{
if(owners_count == 0){
contract_owner = msg.sender;
}
}
//Modifier that only allows owner of the bag to Smart Contract AKA Good to use the function
modifier onlyOwner(){
require(msg.sender == contract_owner);
_;
}
// Add a new product to the blockchain with a new serial
function addNewGoods(bytes32 _model,bytes32 _status, bytes32 _date_manufactured) public returns(bool made) {//Declare Goods struct
setOwner(msg.sender);
model = _model;
status = _status;
date_manufactured = _date_manufactured;
return true;
}
//This function transfer ownership of contract from one entity to another
function transferOwnership(address _newOwner) public onlyOwner(){
require(_newOwner != address(0));
contract_owner = _newOwner;
}
//Set the KEY to uint256 and VALUE owner Ethereum Address
function setOwner(address owner)public{
owners_count += 1 ;
owners[owners_count] = owner;
}
//Get the previous owner in the mappings
function previousOwner()constant public returns(address){
if(owners_count != 0){
uint256 previous_owner = owners_count - 1;
return owners[previous_owner];
}
}
// Getter Methods
function getManufacturer() constant public returns(address){
return contract_owner;
}
function getCurrentOwner() constant public returns(address){
return owners[owners_count] ;
}
function getOwnerCount() constant public returns(uint256){
return owners_count;
}
function getModel() constant public returns(bytes32){
return model;
}
function getStatus() constant public returns(bytes32){
return status;
}
function getDateManufactured() constant public returns(bytes32){
return date_manufactured;
}
}// end of LuxSecure
Javascript to perform the transfer of ownership
function transferOwnership(){
var account_to_transfer = document.getElementById("ethereumaddress").value;
contract.transferOwnership(account_to_transfer,{
from:web3.eth.accounts[0],
gas:4000000
});
}
I don't see any particular mistake in your code. Maybe a bad formatting on the front-side, but can't guess for sure as we have partial front here.
I don't know if it will be some help but sometimes, using truffle, it happened to me to have some functions that returned bad opcode from testrpc/ganache-cli while no apparent error was in the code.
Deleting the ABI, recompiling the smart-contracts to get a brand new ABI and then redeploying the contracts solved the problem.