How to make an API call in solidity using chainlink? - oracle

I need to replace "uint256 player" with the response from the server in my smart contract using chainlink.
Actually, I found similar questions here, but their answers are either outdated or unsuitable in my case.
//Contract based on https://docs.openzeppelin.com/contracts/3.x/erc721
// SPDX-License-Identifier: MyT
pragma solidity ^0.8.4;
import 'https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol';
contract MyNFT is Ownable {
function payToStartGame(uint256 player) external payable {
payable(owner()).transfer(msg.value);
if (player > 10) {
revert("Game started, try again later");
}
}
}
I will be grateful for any help!

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));
}

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

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.

How to test a Solidity exceptions using Hardhat and Chai?

I'm new working with Solidity. I have a very simple contract that is doing some validation
function withdraw(uint amount) external {
uint balance = wallets[msg.sender];
require(balance >= amount, "Pool: not enough balance");
....
and I want to test it so tried sometime like this
try {
await sut.connect(lp1).withdraw(utils.parseUnits("500000000000"))
} catch(e) {
console.log(e)
}
but it's giving me the following error
Uncaught RuntimeError: abort(Error: VM Exception while processing
transaction: reverted with reason string 'Pool: not enough balance').
Build with -s ASSERTIONS=1 for more info.
It seems that my try/catch is not working. I tried expect(....).to.throw() but the result is the same.
It looks like something breaks at VM level and there is nothing to do from JS. I'm using Hardhat, Typescript and Chai.
Any idea? I was trying to find a solution but nothing show up... which is weird, testing these kind of situations is pretty common.
Thanks
I found a way to do it, probably because I'm using types/chai-as-promised.
const withdraw = sut.connect(lp1).withdraw(utils.parseUnits("500"))
await expect(withdraw).eventually.to.rejectedWith(Error, "VM Exception while processing transaction: reverted with reason string 'Pool: not enough balance'")
The trick is not waiting inside expect, and then using eventually.to.rejectedWith
Try this instead. First install ethereum-waffle with your favorite package manager (yarn xD).
import { solidity } from "ethereum-waffle";
import { use, expect } from "hardhat";
use(solidity);
describe("...", async () => {
it("...", async () => {
await expect(erc721.tokenURI(0)).to.be.revertedWith("ERC721: the token does not exist");
});
}
`

Looking for assistance with Pseudocode

I need some help with pseudocode. The question is as follows:
Write pseudocode for a function, processPayment() that processes
payment by customers and commits the system to delivering the promised
product and service. This function may call on other functions,
possibly from other objects. You do not have to describe the called
functions or the classes that they belong to as long the calls are
reasonably explanatory.
Advertising is displayed while the customer
awaits credit approval. (i.e., you can assume that while the function
is waiting for credit card approval to complete, the next step begins
immediately.)
Advertising is removed as soon as credit acceptance or
denial is received. You can assume that the user has already entered
credit card information and is aware of the costs of each option.
I have this as pseudocode:
processPayment()
do displayAdContent();
while paymentConfirmation(bool) = false;
I keep thinking I need something after processPayment(). Any guidance would be appreciated!
You need a lot more than "something after processPayment()." I would do something like this:
ProcessPayment()
{
if(paymentIsValid)
{
do displayAdContent();
if(isInInventory())
{
try
{
do createAndChargeOrder();
do deliverProduct();
do updateInventory();
}
catch
{
do cancelOrder();
do sendFailedOrderNotification();
}
}
else
{
do notifyNotAvailable();
do offerSimilarProduct();
}
do sendConfirmation();
}
else
{
do paymentNotValid();
}
}

Resources