Programming on Solidity setName function (BitDegree) - function

As part of the Bitdegree learning solidity course. I have been asked to do the following:
Modify the function setName in a way that would allow setting the value of name
2.Create a new function named increaseCounter that would increase the value of counter by 10 whenever it is called
I have tried multiple things for setting the name but have had so many issues, I would really appreciate if someone could help me out with this, its so basic but for some reason nothing has been working :(. This is the current code
pragma solidity ^0.4.16;
contract FunctionTest {
bool public foo = true;
string public name;
uint256 public counter = 0;
function setName() public {
//
}
function writeToStorage() {
foo = !foo;
}
function readFromStorageConstant() public constant returns (bool) {
return foo;
}
function readFromStorageView() public view returns (bool) {
return foo;
}
}

For some reason it needs the variable 'name' to be initialized to a string to get it to submit.
pragma solidity ^0.4.16;
contract FunctionTest {
bool public foo = true;
string public name="ChuckNorris";
uint256 public counter = 0;
function setName(string _name) public {
name = _name;
}
function increaseCounter() public {
counter += 10;
}
function writeToStorage() {
foo = !foo;
}
function readFromStorageConstant() public constant returns (bool) {
return foo;
}
function readFromStorageView() public view returns (bool) {
return foo;
}
}

Make sure that you are answering both parts of the question. For some reason in this lesson the setName() fuction won't show that you have completed it correctly until you complete the increaseCounter() function.Here is the solution that helped me advance to the next level.
pragma solidity ^0.4.16;
contract FunctionTest {
bool public foo = true;
string public name;
uint256 public counter = 0;
function setName(string _name) public {
name = _name;
}
function increaseCounter() public {
counter += 10;
}
function writeToStorage() {
foo = !foo;
}
function readFromStorageConstant() public constant returns (bool) {
return foo;
}
function readFromStorageView() public view returns (bool) {
return foo;
}
funciton increaseCounter() {
counter += 10; }
}

Should be pretty straightforward...
pragma solidity ^0.4.16;
contract FunctionTest {
bool public foo = true;
string public name;
uint256 public counter = 0;
function setName(string _name) public {
name = _name;
}
function increaseCounter() public {
counter += 10;
}
function writeToStorage() {
foo = !foo;
}
function readFromStorageConstant() public constant returns (bool) {
return foo;
}
function readFromStorageView() public view returns (bool) {
return foo;
}
}

// SPDX-License-Identifier: nolicense
pragma solidity ^0.8.0;
contract sample{
string public name;
function setName(string memory _newName) public returns(bool){
name =_newName;
return true;
}
function getName() public view returns (string memory){
return name;
}
}

Related

No argument constructor identifier expected

Keep getting Identifier Expected for no-argument constructor
I've tried adding String playerName; and so forth in the constructor to identify.
Also tried this.tp1.playerNamer, and taking away " = null / = 0"
but keep getting same message.
Rest of the code works fine if I take away the constructor
public class KosakowskiTennisPlayer2
{
private String playerName;
private String country;
private int rank;
private int age;
private int wins;
private int losses;
public void setPlayerName(String thePlayerName)
{ playerName = thePlayerName;}
public void setCountry(String theCountry)
{ country = theCountry;}
public void setRank(int theRank)
{ rank = theRank;}
public void setAge(int theAge)
{ age = theAge;}
public void setWins(int theWins)
{ wins = theWins;}
public void setLosses(int theLosses)
{ losses = theLosses;}
// accessor
public String getPlayerName()
{ return playerName;}
public String getCountry()
{ return country;}
public int getRank()
{ return rank;}
public int getAge()
{ return age;}
public int getWins()
{ return wins;}
public int getLosses()
{ return losses;}
KosakowskiTennisPlayer2 tp1 = new KosakowskiTennisPlayer2()
{
tp1.playerName;
tp1.country;
tp1.rank;
tp1.age;
tp1.wins;
tp1.losses;
}
Only with the constructor part is there a problem.

How to fix undeclared identifier even though its present in ERC721Enumerable

I am trying to prepare a solidity smart contract and everything appears fine except a single undeclared error on remix compiler. The error code is as follows:
from solidity:
DeclarationError: Undeclared identifier.
--> contracts/WTest.sol:66:22:
|
66 | uint256 supply = totalSupply();
| ^^^^^^^^^^^
For reference, my code is as follows:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
import "#openzeppelin/contracts/utils/math/SafeMath.sol";
contract WTest is ERC721, ERC721Burnable, Ownable {
using Strings for uint256;
using SafeMath for uint256;
uint256 public mintPrice;
address public blackHoleAddress;
ERC721 public crateContract;
string public baseURI;
string public baseExtension = ".json";
mapping(uint256 => bool) private _crateProcessList;
bool public paused = false;
bool public revealed = false;
uint256 public maxSupply = 5000;
uint256 public maxPrivateSupply = 580;
uint256 public maxMintAmount = 20;
string public notRevealedUri;
event OperationResult(bool result, uint256 itemId);
constructor() ERC721("WTest", "WTST") {}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function setBASEURI(string memory newuri) public onlyOwner {
baseURI = newuri;
}
function setMintPrice(uint256 _mintPrice) public onlyOwner returns(bool success) {
mintPrice = _mintPrice;
return true;
}
function getMintPrice() public view returns (uint256)
{
return mintPrice;
}
function setBlackHoleAddress(address _blackHoleAddress) public onlyOwner returns(bool success) {
blackHoleAddress = _blackHoleAddress;
return true;
}
function setcrateContractAddress(ERC721 _crateContractAddress) public onlyOwner returns (bool success) {
crateContract = _crateContractAddress;
return true;
}
function mint(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
require(msg.value >= mintPrice * _mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
As you can see I have referenced ERC721Enumerable.sol
Any help in understanding where I am going wrong would be greatly appreciated.
You must extend ERC721Enumerable, and only then you can use totalSupply() function.
Your smart contract should be similtar to this:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
import "#openzeppelin/contracts/utils/math/SafeMath.sol";
contract WTest is ERC721, ERC721Enumerable, ERC721Burnable, Ownable {
using Strings for uint256;
using SafeMath for uint256;
uint256 public mintPrice;
address public blackHoleAddress;
ERC721 public crateContract;
string public baseURI;
string public baseExtension = ".json";
mapping(uint256 => bool) private _crateProcessList;
bool public paused = false;
bool public revealed = false;
uint256 public maxSupply = 5000;
uint256 public maxPrivateSupply = 580;
uint256 public maxMintAmount = 20;
string public notRevealedUri;
event OperationResult(bool result, uint256 itemId);
constructor() ERC721("WTest", "WTST") {}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function setBASEURI(string memory newuri) public onlyOwner {
baseURI = newuri;
}
function setMintPrice(uint256 _mintPrice) public onlyOwner returns(bool success) {
mintPrice = _mintPrice;
return true;
}
function getMintPrice() public view returns (uint256)
{
return mintPrice;
}
function setBlackHoleAddress(address _blackHoleAddress) public onlyOwner returns(bool success) {
blackHoleAddress = _blackHoleAddress;
return true;
}
function setcrateContractAddress(ERC721 _crateContractAddress) public onlyOwner returns (bool success) {
crateContract = _crateContractAddress;
return true;
}
function mint(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
require(msg.value >= mintPrice * _mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
// NOTE: Override ERC721Enumerable functions
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
}

Verifying solidity contract on polygonscan

I created a Solidity Contract. What information should go in "Enter the Solidity Contract Code below?"
Below I am also listing the solidity code I used.
I tried putting the code in directly and the website errors out on me.
I am also attaching the link to the contract on polygonscan
https://polygonscan.com/token/0xd1a8ee4c74e0153aa1282967336b4a35f60a8dab
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "#openzeppelin/contracts/access/Ownable.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
contract EmbassyBuddhas is ERC721Enumerable, Ownable {
using Strings for uint256;
string public baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.05 ether;
uint256 public presaleCost = 0.03 ether;
uint256 public maxSupply = 10000;
uint256 public maxMintAmount = 20;
bool public paused = false;
mapping(address => bool) public whitelisted;
mapping(address => bool) public presaleWallets;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
mint(msg.sender, 20);
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// public
function mint(address _to, uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
if (whitelisted[msg.sender] != true) {
if (presaleWallets[msg.sender] != true) {
//general public
require(msg.value >= cost * _mintAmount);
} else {
//presale
require(msg.value >= presaleCost * _mintAmount);
}
}
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(_to, supply + i);
}
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
baseExtension
)
)
: "";
}
//only owner
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setPresaleCost(uint256 _newCost) public onlyOwner {
presaleCost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
maxMintAmount = _newmaxMintAmount;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension)
public
onlyOwner
{
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function whitelistUser(address _user) public onlyOwner {
whitelisted[_user] = true;
}
function removeWhitelistUser(address _user) public onlyOwner {
whitelisted[_user] = false;
}
function addPresaleUser(address _user) public onlyOwner {
presaleWallets[_user] = true;
}
function add100PresaleUsers(address[100] memory _users) public onlyOwner {
for (uint256 i = 0; i < 2; i++) {
presaleWallets[_users[i]] = true;
}
}
function removePresaleUser(address _user) public onlyOwner {
presaleWallets[_user] = false;
}
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{
value: address(this).balance
}("");
require(success);
}
}
if you are having problems verifying contract code is because in your contract you are importing code from others contract, but you are not pasting that code there, I'll recommend you to check how to "flatten" a contract in the tool you are using and paste the flattened contract there
I would prefer to use frameworks such as truffle and hardhat to verify the contract because it will help you to make it easy.
So you can read more details How to verify contract on this link

Error: Returned error: VM Exception while processing transaction: revert when creating with New

I'm using Drizzle and when ever I call createInvestorToken on this contract I get Error: Returned error: VM Exception while processing transaction: revert . Not sure how to debug this. It succeeds in the test, but it won't succeed otherwise.
If I remove the allTokens.push(new InvestmentToken(_name,_symbol,initalSupply,_cost)); it works.
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.21 <0.7.0;
import "#openzeppelin/contracts/token/ERC20/ERC20.sol";
contract InvestmentToken is ERC20{
string public name;
string public symbol;
uint256 public decimals = 0;
uint256 public INITIAL_SUPPLY;
uint256 public cost;
address public parent;
constructor(string memory _name, string memory _symbol, uint256 initalSupply, uint256 _cost) public {
name = _name;
symbol = _symbol;
INITIAL_SUPPLY = initalSupply;
cost=_cost;
parent = msg.sender;
_mint(msg.sender, INITIAL_SUPPLY);
}
function buyToken(address receiver, uint256 amount) public {
if (msg.sender != parent) {
revert("You may only buy through the DPAC token");
}
uint256 tokensLeft = balanceOf(msg.sender);
if (tokensLeft >= amount/cost){
_transfer(msg.sender,receiver, amount/cost);
} else {
revert("There are no more tokens");
}
}
}
contract TheParentToken {
string public name = "DPAC_Token";
string public symbol = "DPAC";
uint256 public decimals = 0;
uint256 public INITIAL_SUPPLY = 10000;
uint256 public numberOfTokens = 0;
mapping(address => bool) public tokenWhiteList;
InvestmentToken[] public allTokens;
address public administrator;
constructor() public {
administrator = msg.sender;
allTokens.push(new InvestmentToken("A","B",1000,1));
allTokens.push(new InvestmentToken("B","C",1000,1));
numberOfTokens = allTokens.length;
}
function createInvestorToken(string memory _name, string memory _symbol, uint256 initalSupply, uint256 _cost) public {
allTokens.push(new InvestmentToken(_name,_symbol,initalSupply,_cost));
numberOfTokens = allTokens.length;
}
function addTokenToWhiteList(address newToken) public {
if(msg.sender != administrator){
revert("Not Admin");
}
tokenWhiteList[newToken]=true;
}
function removeTokenFromWhiteList(address newToken) public {
if(msg.sender != administrator){
revert("Not Admin");
}
tokenWhiteList[newToken]=false;
}
}
In this case the token was hitting the gas limit, and the error wasn't being displayed as the Gas Issue.
I think because it was creating a token the error is suppressed.

Casting an object using 'as' returns null: myObject = newObject as MyObject; // null

I am trying to create a custom object in AS3 to pass information to and from a server, which in this case will be Red5. In the below screenshots you will see that I am able to send a request for an object from as3, and receive it successfully from the java server. However, when I try to cast the received object to my defined objectType using 'as', it takes the value of null. It is my understanding that that when using "as" you're checking to see if your variable is a member of the specified data type. If the variable is not, then null will be returned.
This screenshot illustrates that I am have successfully received my object 'o' from red5 and I am just about to cast it to the (supposedly) identical datatype testObject of LobbyData:
Enlarge
However, when testObject = o as LobbyData; runs, it returns null. :(
Enlarge
Below you will see my specifications both on the java server and the as3 client. I am confident that both objects are identical in every way, but for some reason flash does not think so. I have been pulling my hair out for a long time, does anyone have any thoughts?
AS3 Object:
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.IExternalizable;
import flash.net.registerClassAlias;
[Bindable]
[RemoteClass(alias = "myLobbyData.LobbyData")]
public class LobbyData implements IExternalizable
{
private var sent:int; // java sentinel
private var u:String; // red5 username
private var sen:int; // another sentinel?
private var ui:int; // fb uid
private var fn:String; // fb name
private var pic:String; // fb pic
private var inb:Boolean; // is in the table?
private var t:int; // table number
private var s:int; // seat number
public function setSent(sent:int):void
{
this.sent = sent;
}
public function getSent():int
{
return sent;
}
public function setU(u:String):void
{
this.u = u;
}
public function getU():String
{
return u;
}
public function setSen(sen:int):void
{
this.sen = sen;
}
public function getSen():int
{
return sen;
}
public function setUi(ui:int):void
{
this.ui = ui;
}
public function getUi():int
{
return ui;
}
public function setFn(fn:String):void
{
this.fn = fn;
}
public function getFn():String
{
return fn;
}
public function setPic(pic:String):void
{
this.pic = pic;
}
public function getPic():String
{
return pic;
}
public function setInb(inb:Boolean):void
{
this.inb = inb;
}
public function getInb():Boolean
{
return inb;
}
public function setT(t:int):void
{
this.t = t;
}
public function getT():int
{
return t;
}
public function setS(s:int):void
{
this.s = s;
}
public function getS():int
{
return s;
}
public function readExternal(input:IDataInput):void
{
sent = input.readInt();
u = input.readUTF();
sen = input.readInt();
ui = input.readInt();
fn = input.readUTF();
pic = input.readUTF();
inb = input.readBoolean();
t = input.readInt();
s = input.readInt();
}
public function writeExternal(output:IDataOutput):void
{
output.writeInt(sent);
output.writeUTF(u);
output.writeInt(sen);
output.writeInt(ui);
output.writeUTF(fn);
output.writeUTF(pic);
output.writeBoolean(inb);
output.writeInt(t);
output.writeInt(s);
}
}
Java Object:
package myLobbyData;
import org.red5.io.amf3.IDataInput;
import org.red5.io.amf3.IDataOutput;
import org.red5.io.amf3.IExternalizable;
public class LobbyData implements IExternalizable
{
private static final long serialVersionUID = 115280920;
private int sent; // java sentinel
private String u; // red5 username
private int sen; // another sentinel?
private int ui; // fb uid
private String fn; // fb name
private String pic; // fb pic
private Boolean inb; // is in the table?
private int t; // table number
private int s; // seat number
public void setSent(int sent)
{
this.sent = sent;
}
public int getSent()
{
return sent;
}
public void setU(String u)
{
this.u = u;
}
public String getU()
{
return u;
}
public void setSen(int sen)
{
this.sen = sen;
}
public int getSen()
{
return sen;
}
public void setUi(int ui)
{
this.ui = ui;
}
public int getUi()
{
return ui;
}
public void setFn(String fn)
{
this.fn = fn;
}
public String getFn()
{
return fn;
}
public void setPic(String pic)
{
this.pic = pic;
}
public String getPic()
{
return pic;
}
public void setInb(Boolean inb)
{
this.inb = inb;
}
public Boolean getInb()
{
return inb;
}
public void setT(int t)
{
this.t = t;
}
public int getT()
{
return t;
}
public void setS(int s)
{
this.s = s;
}
public int getS()
{
return s;
}
#Override
public void readExternal(IDataInput input)
{
sent = input.readInt();
u = input.readUTF();
sen = input.readInt();
ui = input.readInt();
fn = input.readUTF();
pic = input.readUTF();
inb = input.readBoolean();
t = input.readInt();
s = input.readInt();
}
#Override
public void writeExternal(IDataOutput output)
{
output.writeInt(sent);
output.writeUTF(u);
output.writeInt(sen);
output.writeInt(ui);
output.writeUTF(fn);
output.writeUTF(pic);
output.writeBoolean(inb);
output.writeInt(t);
output.writeInt(s);
}
}
AS3 Client:
public function refreshRoom(event:Event)
{
var resp:Responder=new Responder(handleResp,null);
ncLobby.call("getLobbyData", resp, null);
}
public function handleResp(o:Object):void
{
var testObject:LobbyData=new LobbyData;
testObject = o as LobbyData;
trace(testObject);
}
Java Client
public LobbyData getLobbyData(String param)
{
LobbyData lobbyData1 = new LobbyData();
lobbyData1.setSent(5);
lobbyData1.setU("lawlcats");
lobbyData1.setSen(5);
lobbyData1.setUi(5);
lobbyData1.setFn("lulz");
lobbyData1.setPic("lulzagain");
lobbyData1.setInb(true);
lobbyData1.setT(5);
lobbyData1.setS(5);
return lobbyData1;
}
As you already figured out, you should use registerClassAlias as the RemoteClass works out of the box only for Flex projects (as bindable, etc).
Be sure to call registerClassAlias before any serializing / deserializing occurs.
Also, the debugger is showing you the actual tipe of your "o" parameter, which is object. This shows that the player is not correctly mapping the AMF serialized object's class to any of your classes (so, by default, it goes with Object). You should see a LobbyData object in the debugger; otherwise, no matter how you cast / coerce it, it won't work.
The objet needs to be declared before the responder is called.
public function refreshRoom(event:Event)
{
var testObject:LobbyData=new LobbyData;
var resp:Responder=new Responder(handleResp,null);
ncLobby.call("getLobbyData", resp, null);
}
public function handleResp(o:Object):void
{
testObject = o as LobbyData;
trace(testObject);
}
Actually if you want to workaround the type casting you can simply add this to your constructor:
public function dataAwareObject(o:* = null)
{
//TODO: implement function
super();
if(o){
for(var a:* in o)
this[a] = o[a];
}
}
}
Works like a charm.