What is balanceRecived in solidity? what it will be strore? - methods

i am begginer can any one explain me what is balanceRecived in solidity? what it will be strore?
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.1;
contract SendMoneyExample {
uint public balanceReceived;
function receiveMoney() public payable {
balanceReceived += msg.value;
}
function getBalance() public view returns(uint) {
return address(this).balance;
}
function withdrawMoney() public {
address payable to = payable(msg.sender);
to.transfer(getBalance());
}
}

Each time when someone executes the receiveMoney() function, it happens as a result of a transaction.
A transaction can hold value in the form of the network native currency. Your question is tagged Ethereum, and the native currency for the Ethereum network is ETH. (If the contract was on the Binance Smart Chain network, the native currency would be BNB, the Tron network has TRX, and so on...)
So each time the receiveMoney() function is executed, in adds the current transaction value to the total number hold in balanceReceived.
Example:
First transaction executing receiveMoney(), sending along 1 wei (the smallest unit of ETH). The value of balanceReceived becomes 1.
Second transaction executing receiveMoney(), sending along 5 wei. The value of balanceReceived becomes 6.

Related

How to use Chainlink AggregatorV3Interface with UUPSUpgradeable?

Will Chainlink's AggregatorV3Interface.sol work with an OpenZeppelin upgradable contract?
Do I place the
"priceFeed =
AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331);"
inside the "initializer{}"?
I would like the address "0x9326BFA02ADD2366b30bacB125260Af641031331"
to be upgradable in the next version of the smart contract.
Is there already a way to do so?
Thank you!
Motivation & Justification
I hope that it makes sense to want to "getLatestPrice()" within the smart contract of a new token.
Before deployment, there is no way of knowing the new token's address.
I would like to change the address using the OpenZeppelin upgradable contract under the UUPS proxy pattern.
Is there any example online to update
priceFeed =
AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); //
Kovan Testnet
on version 2 of the smart contract?
Thank you!
Important Links:
OpenZeppelin Contracts Wizard
get-the-latest-price using Chainlink's AggregatorV3Interface
Deploying an UUPS Upgradable Contract
I have no idea how to work on version 2 of an UUPS Upgradable Contract.
This is where I got stuck using Chainlink's AggregatorV3Interface.sol with every feature selected on OpenZeppelin Contracts Wizard:
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4;
import
"./#openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "./#openzeppelin/contracts-
upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol";
import "./#openzeppelin/contracts-
upgradeable/token/ERC20/extensions/ERC20SnapshotUpgradeable.sol";
import
"./#openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import
"./#openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import
"./#openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-
ERC20PermitUpgradeable.sol"; import "./#openzeppelin/contracts-
upgradeable/token/ERC20/extensions/ERC20VotesUpgradeable.sol"; import
"./#openzeppelin/contracts-
upgradeable/token/ERC20/extensions/ERC20FlashMintUpgradeable.sol";
import
"./#openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import
"./#openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import
"#chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract UpToken is Initializable, ERC20Upgradeable,
ERC20BurnableUpgradeable, ERC20SnapshotUpgradeable,
OwnableUpgradeable, PausableUpgradeable, ERC20PermitUpgradeable,
ERC20VotesUpgradeable, ERC20FlashMintUpgradeable, UUPSUpgradeable {
/// #custom:oz-upgrades-unsafe-allow constructor AggregatorV3Interface
internal priceFeed; constructor() initializer {
priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); //
Kovan Testnet }
function initialize() initializer public {
__ERC20_init("UpToken", "UPT");
__ERC20Burnable_init();
__ERC20Snapshot_init();
__Ownable_init();
__Pausable_init();
__ERC20Permit_init("UpToken");
__ERC20FlashMint_init();
__UUPSUpgradeable_init(); }
function snapshot() public onlyOwner {
_snapshot(); }
function pause() public onlyOwner {
_pause(); }
function unpause() public onlyOwner {
_unpause(); }
function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount); }
function _beforeTokenTransfer(address from, address to, uint256
amount)
internal
whenNotPaused
override(ERC20Upgradeable, ERC20SnapshotUpgradeable) {
super._beforeTokenTransfer(from, to, amount); }
function _authorizeUpgrade(address newImplementation)
internal
onlyOwner
override {}
// The following functions are overrides required by Solidity.
function _afterTokenTransfer(address from, address to, uint256 amount)
internal
override(ERC20Upgradeable, ERC20VotesUpgradeable) {
super._afterTokenTransfer(from, to, amount); }
function _mint(address to, uint256 amount)
internal
override(ERC20Upgradeable, ERC20VotesUpgradeable) {
super._mint(to, amount); }
function _burn(address account, uint256 amount)
internal
override(ERC20Upgradeable, ERC20VotesUpgradeable) {
super._burn(account, amount); }
function getLatestPrice() public view returns (int) {
(
/uint80 roundID/,
int price,
/uint startedAt/,
/uint timeStamp/,
/uint80 answeredInRound/
) = priceFeed.latestRoundData();
return price; }
}
Recommend you use hardhat with the upgrades plugin (https://docs.openzeppelin.com/contracts/4.x/upgradeable) to achieve this. When you deploy it the first time using hardhat, it will deploy the proxy, the implementation contract (i.e. your token contract) and an admin contract.
See 20:23 onwards in this video: https://www.youtube.com/watch?v=bdXJmWajZRY&t=15s . In fact maybe watch that entire video to get a sense of how to use hardhat with OZ upgradeable contracts.
Then when you get your token contract address, update the token contract as V2, add the contract address as a state variable and (optionally) add a setter function that gives you the ability to update that state variable in future, and deploy V2. You can see how to deploy V2 in that same video I linked above, at [24:30] or so.

In solidity ,can push command be used for adding an element to a byte data type , this guy on yt did , on the net it says its only for dynamic array?

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract dynamicsizedbyte{
bytes public by1;
function setvalue() public {
by1="abcdefgh";
}
function pushelement() public {
by1.push(10);
}
}
im getting this error
TypeError: Member "push" not found or not visible after argument-dependent lookup in bytes storage ref.
The best high-level approach I could come up with is overriding the whole value with a newly-created byte array. Hoping someone finds a more efficient solution, should be possible using the Solidity assembly.
function pushelement() public {
by1 = abi.encodePacked(by1, bytes1(0x10));
}

Chainlink Keeper not performing upkeep

I have a contract that is using Chainlink keepers for upkeep but the checkUpKeep/performUpkeep is not running. I have sufficiently funded the upkeep to ensure it has a high balance. The code from the contract was previously deployed, but now contains a minor change (outside the Chainlink functions), and the previous contract is receiving upkeeps. My code for checkUpKeep and performUpKeep are below:
function **checkUpkeep**(bytes calldata /* checkData */) external view override returns (bool upkeepNeeded, bytes memory /* performData */) {
if(lottery_state == LOTTERY_STATE.OPEN){
upkeepNeeded = (block.timestamp - lastTimeStamp) >= duration;
}
else{
upkeepNeeded = false;
}
}
function **performUpkeep**(bytes calldata /* performData */) external override {
require(msg.sender == 0x4Cb093f226983713164A62138C3F718A5b595F73);
lottery_state = LOTTERY_STATE.DRAWING;
Random(random).getRandomNumber();
}
As I mentioned earlier, this code is being used in another contract which is currently receiving upkeep so I am puzzled as to why it is not working in the new contract.
If your upkeeps are not being performed make sure to double-check the next items:
Are Chainlink Keepers currently available on the network you are deploying to?
Is your smart contract KeeperCompatible?
Call checkUpkeep. Did it return true or false?
Can you performUpkeep?
Did you register your contract for upkeeps?
Did you fund it?

Multiple indexed event fields are not supported by web3j?

I'm having Ethereum smart contract with function:
event onPledged(uint indexed featureKey, uint date, address backer, uint256 amount);
...
function pledge(uint featureKey) public
payable
withState(featureKey, State.Funding)
{
...
// event
onPledged(featureKey, now, backer, pledgeAmount);
...
}
I'm having java test (using web3j and web3j-maven-plugin to generate smart contract java wrapper) to call pledge() that checks events:
// pledge
logger.info("Pledging by backer ...");
TransactionReceipt pledgeReceipt = pledgerContract.pledge(featureKey, fixedPledgeAmount).send();
List<AppetissimoContract.OnPledgedEventResponse> pledgedEvents = minerContract.getOnPledgedEvents(pledgeReceipt);
assertEquals(1, pledgedEvents.size()); // true
If i change backer event field to be indexed the test starts to fail:
event onPledged(uint indexed featureKey, uint date, address indexed backer, uint256 amount);
Now it's fails as there were no events (0):
assertEquals(1, pledgedEvents.size()); // false, size() is 0
In solidity docs it's written that up to 3 fields can be indexed:
> Up to three parameters can receive the attribute indexed which will cause the respective arguments to be searched for: It is possible to filter for specific values of indexed arguments in the user interface.
Is it web3j issue? Does using of indexed attribute require more gas (so reaching gas limit can be the reson)?
this is an outstanding bug with web3j. Right now you have to order all of the indexed parameters before the non-indexed parameters to work around this.

Domain Driven Design - complex validation of commands across different aggregates

I've only began with DDD and currently trying to grasp the ways to do different things with it. I'm trying to design it using asynchronous events (no event-sourcing yet) with CQRS. Currently I'm stuck with validation of commands. I've read this question: Validation in a Domain Driven Design , however, none of the answers seem to cover complex validation across different aggregate roots.
Let's say I have these aggregate roots:
Client - contains list of enabled services, each service can have a value-object list of discounts and their validity.
DiscountOrder - an order to enable more discounts on some of the services of given client, contains order items with discount configuration.
BillCycle - each period when bills are generated is described by own billcycle.
Here's the usecase:
Discount order can be submitted. Each new discount period in discount order should not overlap with any of BillCycles. No two discounts of same type can be active at the same time on one service.
Basically, using Hibernate in CRUD style, this would look something similar to (java code, but question is language-agnostic):
public class DiscountProcessor {
...
#Transactional
public void processOrder(long orderId) {
DiscOrder order = orderDao.get(orderId);
BillCycle[] cycles = billCycleDao.getAll();
for (OrderItem item : order.getItems()) {
//Validate billcycle overlapping
for (BillCycle cycle : cycles) {
if (periodsOverlap(cycle.getPeriod(), item.getPeriod())) {
throw new PeriodsOverlapWithBillCycle(...);
}
}
//Validate discount overlapping
for (Discount d : item.getForService().getDiscounts()) {
if (d.getType() == item.getType() && periodsOverlap(d.getPeriod(), item.getPeriod())) {
throw new PeriodsOverlapWithOtherItems(...);
}
}
//Maybe some other validations in future or stuff
...
}
createDiscountsForOrder(order);
}
}
Now here are my thoughts on implementation:
Basically, the order can be in three states: "DRAFT", "VALIDATED" and "INVALID". "DRAFT" state can contain any kind of invalid data, "VALIDATED" state should only contain valid data, "INVALID" should contain invalid data.
Therefore, there should be a method which tries to switch the state of the order, let's call it order.validate(...). The method will perform validations required for shift of state (DRAFT -> VALIDATED or DRAFT -> INVALID) and if successful - change the state and transmit a OrderValidated or OrderInvalidated events.
Now, what I'm struggling with, is the signature of said order.validate(...) method. To validate the order, it requires several other aggregates, namely BillCycle and Client. I can see these solutions:
Put those aggregates directly into the validate method, like
order.validateWith(client, cycles) or order.validate(new
OrderValidationData(client, cycles)). However, this seems a bit
hackish.
Extract the required information from client and cycle
into some kind of intermediate validation data object. Something like
order.validate(new OrderValidationData(client.getDiscountInfos(),
getListOfPeriods(cycles)).
Do validation in a separate service
method which can do whatever it wants with whatever aggregates it
wants (basically similar to CRUD example above). However, this seems
far from DDD, as method order.validate() will become a dummy state
setter, and calling this method will make it possible to bring an
order unintuitively into an corrupted state (status = "valid" but
contains invalid data because nobody bothered to call validation
service).
What is the proper way to do it, and could it be that my whole thought process is wrong?
Thanks in advance.
What about introducing a delegate object to manipulate Order, Client, BillCycle?
class OrderingService {
#Injected private ClientRepository clientRepository;
#Injected private BillingRepository billRepository;
Specification<Order> validSpec() {
return new ValidOrderSpec(clientRepository, billRepository);
}
}
class ValidOrderSpec implements Specification<Order> {
#Override public boolean isSatisfied(Order order) {
Client client = clientRepository.findBy(order.getClientId());
BillCycle[] billCycles = billRepository.findAll();
// validate here
}
}
class Order {
void validate(ValidOrderSpecification<Order> spec) {
if (spec.isSatisfiedBy(this) {
validated();
} else {
invalidated();
}
}
}
The pros and cons of your three solutions, from my perspective:
order.validateWith(client, cycles)
It is easy to test the validation with order.
#file: OrderUnitTest
#Test public void should_change_to_valid_when_xxxx() {
Client client = new ClientFixture()...build()
BillCycle[] cycles = new BillCycleFixture()...build()
Order order = new OrderFixture()...build();
subject.validateWith(client, cycles);
assertThat(order.getStatus(), is(VALID));
}
so far so good, but there seems to be some duplicate test code for DiscountOrderProcess.
#file: DiscountProcessor
#Test public void should_change_to_valid_when_xxxx() {
Client client = new ClientFixture()...build()
BillCycle[] cycles = new BillCycleFixture()...build()
Order order = new OrderFixture()...build()
DiscountProcessor subject = ...
given(clientRepository).findBy(client.getId()).thenReturn(client);
given(cycleRepository).findAll().thenReturn(cycles);
given(orderRepository).findBy(order.getId()).thenReturn(order);
subject.processOrder(order.getId());
assertThat(order.getStatus(), is(VALID));
}
#or in mock style
#Test public void should_change_to_valid_when_xxxx() {
Client client = mock(Client.class)
BillCycle[] cycles = array(mock(BillCycle.class))
Order order = mock(Order.class)
DiscountProcessor subject = ...
given(clientRepository).findBy(client.getId()).thenReturn(client);
given(cycleRepository).findAll().thenReturn(cycles);
given(orderRepository).findBy(order.getId()).thenReturn(order);
given(client).....
given(cycle1)....
subject.processOrder(order.getId());
verify(order).validated();
}
order.validate(new OrderValidationData(client.getDiscountInfos(),
getListOfPeriods(cycles))
Same as the above one, you still need to prepare data for both OrderUnitTest and discountOrderProcessUnitTest. But I think this one is better as order is not tightly coupled with Client and BillCycle.
order.validate()
Similar to my idea if you keep validation in the domain layer. Sometimes it is just not any entity's responsibility, consider domain service or specification object.
#file: OrderUnitTest
#Test public void should_change_to_valid_when_xxxx() {
Client client = new ClientFixture()...build()
BillCycle[] cycles = new BillCycleFixture()...build()
Order order = new OrderFixture()...build();
Specification<Order> spec = new ValidOrderSpec(clientRepository, cycleRepository);
given(clientRepository).findBy(client.getId()).thenReturn(client);
given(cycleRepository).findAll().thenReturn(cycles);
subject.validate(spec);
assertThat(order.getStatus(), is(VALID));
}
#file: DiscountProcessor
#Test public void should_change_to_valid_when_xxxx() {
Order order = new OrderFixture()...build()
Specification<Order> spec = mock(ValidOrderSpec.class);
DiscountProcessor subject = ...
given(orderingService).validSpec().thenReturn(spec);
given(spec).isSatisfiedBy(order).thenReturn(true);
given(orderRepository).findBy(order.getId()).thenReturn(order);
subject.processOrder(order.getId());
assertThat(order.getStatus(), is(VALID));
}
Do the 3 possible states reflect your domain or is that just extrapolation ? I'm asking because your sample code doesn't seem to change Order state but throw an exception when it's invalid.
If it's acceptable for the order to stay DRAFT for a short period of time after being submitted, you could have DiscountOrder emit a DiscountOrderSubmitted domain event. A handler catches the event and (delegates to a Domain service that) examines if the submit is legit or not. It would then issue a ChangeOrderState command to make the order either VALIDATED or INVALID.
You could even suppose that the change is legit by default and have processOrder() directly take it to VALIDATED, until proven otherwise by a subsequent INVALID counter-order given by the validation service.
This is not much different from your third solution or Hippoom's one though, except every step of the process is made explicit with its own domain event. I guess that with your current aggregate design you're doomed to have a third party orchestrator (as un-DDD and transaction script-esque as it may sound) that controls the process, since the DiscountOrder aggregate doesn't have native access to all information to tell if a given transformation is valid or not.

Resources