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.