Skip to content

Instantly share code, notes, and snippets.

@Astroneko404
Last active January 31, 2021 15:48
Show Gist options
  • Save Astroneko404/5dbb23f63699bb39bdadbf50583bdef7 to your computer and use it in GitHub Desktop.
Save Astroneko404/5dbb23f63699bb39bdadbf50583bdef7 to your computer and use it in GitHub Desktop.
Property tests of string variables in Solidity
pragma solidity >=0.7.0 <0.8.0;
contract ChangeByte {
bytes8 text = 'abcdefgh';
// 0x6162636465666768
function getText() public view returns(bytes8) {
return text;
}
// 0x61
function change1() public view returns(bytes1) {
return bytes1(text);
}
// 0x6162
function change2() public view returns(bytes2) {
return bytes2(text);
}
function fixed2dynamic() public view returns(bytes memory) {
bytes memory newText = new bytes(text.length);
for (uint i = 0; i < text.length; i++) {
newText[i] = text[i];
}
return newText;
}
}
pragma solidity >=0.7.0 <0.8.0;
contract PayTest {
// Ether will be transferred from account to contract
function pay() public payable {
}
// "this" will be pointed to the contract
function getThis() public view returns(address) {
return address(this);
}
function getBalance() public view returns(uint) {
return address(this).balance;
}
// This address could be either account or deployed contracts
function getBalanceAcc() public view returns(uint) {
address account = 0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db;
return account.balance;
}
function transfer() public payable {
address payable acc = 0x78731D3Ca6b7E34aC0F824c42a7cC18A495cabaB; // Transfer from current account to this one
acc.transfer(msg.value);
}
}
pragma solidity >=0.7.0 <0.8.0;
/**
* Some String and Byte type test
*/
contract StringByte {
string private text1 = 'abcdefgh';
// This will not cost ether with the "view" modifier
function getString() public view returns(string memory) {
return text1;
}
function getLength() public view returns(uint) {
// return text1.length; -> Can't do This
return bytes(text1).length;
}
// This will cost ether as it modifies values on the chain
function setValue(string memory newStr) public {
text1 = newStr;
}
function getChar(uint idx) public view returns(bytes1) {
if (idx >= 0 && idx < getLength()) {
// return text1[0]; -> Can't do this
return bytes(text1)[idx];
}
else {
return '';
}
}
function setChar(uint idx, bytes1 a) public {
if (idx >= 0 && idx < getLength()) {
bytes(text1)[idx] = a;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment