getting empty result form smart-contract using web3 - solidity

im new to web3 and solidity in general but I've been following the web documentation on calling contract methods from web3
my solidity smart-contract:
pragma solidity ^ 0.5.0;
contract Royalties {
string public name = "RoyaltiesContract";
uint public nextArtistId = 1;
uint public nextSongId = 0;
uint public nextCollabId = 0;
mapping(uint => Artist) public Artists;
struct Artist {
uint id;
string ArtistName;
address ArtistAddress;
}
function createArtist(string memory ArtistName,address Artistaddress) public returns(uint id, string memory Name, address Address) {
Artists[nextArtistId] = Artist(nextArtistId,ArtistName, Artistaddress);
nextArtistId++;
return(nextArtistId,ArtistName, Artistaddress);
}
function getArtist(uint id) view public returns(uint, string memory , address){
return(Artists[id].id,Artists[id].ArtistName, Artists[id].ArtistAddress);
}
}
my web3 code after doing all the configs :
shoot(royalties) {
const createArtist = royalties.methods.createArtist("DMX","0x518251583591f3DE330Eb539AB64b6E95C1EE5c5").call().then(
function(result){
console.log(result)
},
royalties.methods.getArtist(1).call({defaultBlock :'latest'}).then(console.log)
)
}
keep in mind an artist with id:1 already exist the above shoot() function is trigged on-click now the first console.log which is createArtist method returns the result fine same as smart-contract like this:
Result {0: "2", 1: "DMX", 2: "0x518251583591f3DE330Eb539AB64b6E95C1EE5c5", id: "2", Name: "DMX", Address: "0x518251583591f3DE330Eb539AB64b6E95C1EE5c5"}
but the second console.log which is getArtist(1) method returns keep in mind an artist with id:1 already:
Result {0: "0", 1: "", 2: "0x0000000000000000000000000000000000000000"}
thank you for taking the time to read my question.

You need to interact with the contract function createArtist() using send(), not call().
send() sends a transaction, which effectively allows for writing into the contract storage.
If you haven't configured your web3 defaultSender, you'll also need to pass it an options object containing at least {from: <address>}, so that web3 knows from which address you want to send (and sign - so you need to pass its private key to web3 as well) the transaction.
call() doesn't send a transaction, just reads data. So you can safely use it for the getArtist() view function call.

Related

How to run multiples contracts functionalities in a single contract Solidity

I'm new to Solidity but I can't find much information about my problem.
For example, I want to make different contracts for different functionalities (I see them as classes)
For example
Main contract
// SPDX-License-Identifier: None
pragma solidity >=0.8.6;
import "./AuthContract.sol";
contract Contract {
string public message;
constructor() {
message = "test";
}
function getMessage() public view returns(string memory) {
return message;
}
}
and second contract
contract Auth {
struct UserDetail {
address addr;
string name;
string password;
string CNIC;
bool isUserLoggedIn;
}
mapping(address => UserDetail) user;
// user registration function
function register(
address _address,
string memory _name,
string memory _password,
string memory _cnic
) public returns (bool) {
require(user[_address].addr != msg.sender);
user[_address].addr = _address;
user[_address].name = _name;
user[_address].password = _password;
user[_address].CNIC = _cnic;
user[_address].isUserLoggedIn = false;
return true;
}
// user login function
function login(address _address, string memory _password)
public
returns (bool)
{
if (
keccak256(abi.encodePacked(user[_address].password)) ==
keccak256(abi.encodePacked(_password))
) {
user[_address].isUserLoggedIn = true;
return user[_address].isUserLoggedIn;
} else {
return false;
}
}
// check the user logged In or not
function checkIsUserLogged(address _address) public view returns (bool) {
return (user[_address].isUserLoggedIn);
}
// logout the user
function logout(address _address) public {
user[_address].isUserLoggedIn = false;
}
}
How could I use the functionalities from that contract in the main contract?
Is such a thing possible in the blockchain?
I am quite new here also but i can solve your problem, if not solve i can lead you to a good path .
so firstly you said you want to create multiple contract for different functionalities, this is good but keep in my you are going to exhaust a lot of gas.
so the answer to your problem is easy you can just read it and implement it.
if you want to use a contract in the Another contract (main in your case) you can do it in two ways(according to my knowledge there might be other).
using new keyword
using address of your previously deployed contract
we will be using the First case as i suppose you havenot deployed the second contract yet
In Order to do it you can use
Auth myObj=new Auth();
This will create a new instance of the contract Auth in your main contract and now you can use the Auth contract's function in your Main contract.you can create a function copy the above line and you can use the Functions using dot operator.
myObj.register(_address,_name,moreandmore);
I believe this will solve your problem if not you can ask it.
Thank You!

How to test the Solidity-By-Example Mapping smart contract in Remix?

I want to test the following code in Remix. But what is the procedure?
What do I put in the input field for the function labeled set?
Mapping.sol
// https://solidity-by-example.org/mapping
// Mapping
// Maps are created with the syntax mapping(keyType => valueType).
// The keyType can be any built-in value type, bytes, string, or any contract.
// valueType can be any type including another mapping or an array.
// Mappings are not iterable.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
contract Mapping {
// Mapping from address to uint
mapping(address => uint) public myMap;
function get(address _addr) public view returns (uint) {
// Mapping always returns a value.
// If the value was never set, it will return the default value.
return myMap[_addr];
}
function set(address _addr, uint _i) public {
// Update the value at this address
myMap[_addr] = _i;
}
function remove(address _addr) public {
// Reset the value to the default value.
delete myMap[_addr];
}
}
contract NestedMapping {
// Nested mapping (mapping from address to another mapping)
mapping(address => mapping(uint => bool)) public nested;
function get(address _addr1, uint _i) public view returns (bool) {
// You can get values from a nested mapping
// even when it is not initialized
return nested[_addr1][_i];
}
function set(
address _addr1,
uint _i,
bool _boo
) public {
nested[_addr1][_i] = _boo;
}
function remove(address _addr1, uint _i) public {
delete nested[_addr1][_i];
}
}
This code came from Solidity by Example.
When I implement it on Remix, I get the following screen.
At this point, to test it, I think I need to map an address to a uint256, so I enter the following in the field next to the set button:
["0xcf646ed6e21fd0756ec45a6be5e1057fc24a1b8308175ff0b9f97f565b594eb3", 7439]
The value of the address was a randomly generated hash (I suspect the random hash might be a problem?)
I expect to see the set function render the value 7439. But, instead, it throws the following error:
transact to Mapping.set errored: Error encoding arguments: Error: invalid address (argument="address", value=["0xcf646ed6e21fd0756ec45a6be5e1057fc24a1b8308175ff0b9f97f565b594eb3",7439], code=INVALID_ARGUMENT, version=address/5.5.0) (argument=null, value=["0xcf646ed6e21fd0756ec45a6be5e1057fc24a1b8308175ff0b9f97f565b594eb3",7439], code=INVALID_ARGUMENT, version=abi/5.5.0)
What am I doing wrong?
You have generated a random SHA-256 that is of the format of a valid address, but it doesn't exist on the Remix's browser-based (Javascript VM) chain as any account. If it does, you might be just lucky.
If you want to use valid addresses that do exist on the browser-based VM chain, copy and use the addresses in the account section.

contracts/3_Ballot.sol:33:37: TypeError: Named argument does not match function declaration

from solidity:
contracts/3_Ballot.sol:33:37: TypeError: Named argument does not match function declaration.
Request memory newRequest = Request({
^ (Relevant source part starts here and spans across multiple lines).
I get this error every time. What should i do for the solve it?
pragma solidity ^0.4.17;
contract Campaign {
struct Request {
string description;
uint value;
address recipient;
bool complete;
}
Request[] public requests;
address public manager;
uint public minimumContirbution;
address[] public approvers;
modifier restricted() {
require (msg.sender == manager);
_;
}
function Campaign (uint minimum) public {
manager = msg.sender;
minimumContirbution = minimum;
}
function contribute () public payable {
require(msg.value > minimumContirbution);
approvers.push(msg.sender);
}
function createRequest(string description, uint value, address recipient) restricted public {
Request memory newRequest = Request({
description: description,
value: value,
restricted: restricted,
complete: false
});
requests.push(newRequest);
}
}
You can define the Request struct in this way and push it into requests array:
function createRequest(string description, uint value, address recipient) restricted public {
Request memory newRequest = Request(description, value, recipient, false);
requests.push(newRequest);
}
In this way, you can add the struct into your array and can retrieve with all parameters setted previously.
Because you're are using wrong argument(restricted) inside you Request type
try this:
Request memory newRequest = Request({
descritption: descritpion,
value: value,
recipient: recipient,
complete: false
});

Truffle test in solidity with sending value

duplicating my question from SA:
I have a simple contract with public function, that can receive value and do something based on that value:
pragma solidity >= 0.8.0 < 0.9.0;
contract ContractA {
uint public boughtItems = 0;
uint price = 10;
address [] buyers;
function buySomething() public payable {
require(msg.value >= price, "Sent value is lower");
boughtItems++;
buyers.push(msg.sender);
}
}
and in test folder of my Truffle project I have test contract:
pragma solidity >=0.8.0 <0.9.0;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/TicketsRoutes.sol";
contract TestTicketsRoutes {
ContractA instance;
address account1 = 0xD8Ce37FA3A1A61623705dac5dCb708Bb5eb9a125;
function beforeAll() public {
instance = new ContractA();
}
function testBuying() public {
//Here I need to invoke buySomething with specific value from specific address
instance.buySomething();
Assert.equal(instance.boughtItems, 1, "Routes amount is not equal");
}
}
How do I invoke function of ContractA in my TestContractA with passing value and sender?
You can use the low-level call() Solidity function to pass a value.
(bool success, bytes memory returnedData) = address(instance).call{value: 1 ether}(
abi.encode(instance.buySomething.selector)
);
But, in order to execute the buySomething() function from a different sender, you need to send it from a different address than the TestTicketsRoutes deployed address.
So you'll need to change your approach and perform the test from an off-chain script (instead of the on-chain test contract) that allows you to sign the transaction from a different sender. Since you tagged the question truffle, here's an example of executing a contract function using the Truffle JS suite (docs).
const instance = await MyContract.at(contractAddress);
const tx = await instance.buySomething({
from: senderAddress,
value: web3.toWei(1, "ether")
});

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.