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? - byte

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

Related

How to encode arguments in AssemblyScript when calling Aurora contract from Near blockchain?

I'm trying to call a contract located in Aurora from a contract located in Near. I'm using AssemblyScript and I'm struggling with passing arguments to the Aurora contract itself. I receive ERR_BORSH_DESERIALIZE panic from the Aurora contract. Can anybody help me with figuring out how I would encode arguments? Here is sample code:
import { BorshSerializer } from '#serial-as/borsh'
#serializable
class FunctionCallArgs {
contract: Uint8Array;
input: Uint8Array;
}
export function myFunction(): void {
const args: FunctionCallArgs = {
contract: util.stringToBytes(contractAddress),
input: util.stringToBytes(abiEncodedFn),
};
const argsBorsh = BorshSerializer.encode(args);
ContractPromise.create("aurora", "call", argsBorsh, 100);
}
I managed to find a solution. The flow of calling the contract was right, however I had two errors in implementation.
Wrong conversion of the contract address to 20 byte array. My custom implementation of the function a bit verbose, so here is a single line JS script that does the same:
Buffer.from(contractAddress.substring(2), 'hex') // removing 0x prefix is mandatory
"#serial-as/borsh" doesn't deserialize fixed length arrays. So I had to convert contractAddress (which is Uint8Array after converting it to bytes in 1st point) to StaticArray(20), like this:
const contract = hexToBytes(tokenAddress).reduce((memo, v, i) => {
memo[i] = <u8>v;
return memo;
}, new StaticArray<u8>(20);
And finally monkey-patched "encode_static_array" method in the library to not allocate space before adding bytes to buffer. So removed:
encode_static_array<T>(value: StaticArray<T>): void {
...
this.buffer.store<u32>(value.length); // remove this line
...
}

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.

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 pursuade the ApiExplorer to create documentation for ExpandoObject?

I've created a very neat way of implementing a PATCH method for my Web.API project by making use of an ExpandoObject as a parameter. As illustrated below:
[HttpPatch, Route("api/employee/{id:int}")]
public IHttpActionResult Update(int id, [FromBody] ExpandoObject employee)
{
var source = Repository.FindEmployeeById(id);
Patch(employee, source);
Repository.SaveEmployee(source);
return Ok(source);
}
However, when generating documentation ApiExplorer is at a loss as to what to do with the ExpandoObject, which is totally understandable. Would anyone have any ideas on how to manipulate the ApiExplorer to provide some sensible documentation?
My idea was to maybe introduce an new attribute which points to the actual Type that is expected:
public IHttpActionResult Update(int id, [FromBody, Mimics(typeof(Employee))] ExpandoObject employee)
{
...
}
But I have no idea where to start, any ideas or suggestions are welcome.
So this has been the source of some late evenings in order to get the Api Explorer to play along with our developed Http Patch mechanism. Truth be told, I'd probably should do a bit of a proper write up to full explain the mechanics behind the whole idea. But for those of you who landed on this page because you want the Api explorer to use a different type in the documentation, this is where you need to look:
Open HelpPageConfigurationExtensions.cs and locate the following method:
//File: Areas/HelpPage/HelpPageConfigurationExtensions.cs
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
....
}
this is the location where the parameter information is available to you and also provides you with the ability to replace/substitute parameter information with something else. I ended up doing the following to handle my ExpandoObject parameter issue:
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
// do something different when dealing with parameters
// of type ExpandObject.
if (parameterType == typeof(ExpandoObject))
{
// if a request-type-attribute is defined, assume the parameter
// is the supposed to mimic the type defined.
var requestTypeAttribute = apiParameter.ParameterDescriptor.GetCustomAttributes<RequestTypeAttribute>().FirstOrDefault();
if (requestTypeAttribute != null)
{
parameterType = requestTypeAttribute.RequestType;
}
}
}
Just, note that the RequestTypeAttribute is something I devised. My WebApi endpoint looks like this now:
public IHttpActionResult Update(int id,
[FromBody, RequestType(typeof(Employee))] ExpandoObject employee)
Thank you to everyone who took time to look into the problem.

Custom memory allocator for OpenCV

Is it possible to set a custom allocator for OpenCV 2.3.1? I have a memory pool created and I want OpenCV to use that pool for what it needs.
Is that possible?
If it is, how can it be done?
Updated:
I made some developments since last answer, but I still have some problems.
This is the code I have now:
CvAllocFunc allocCV()
{
return (CvAllocFunc) MEMPOOL->POOLalloc(sz);
}
CvFreeFunc deallocCV()
{
return (CvFreeFunc) MEMPOOL->POOLfree(ptr);
}
...
cvSetMemoryManager(allocCV(),deallocCV(),data);
Now, my question is, how can I have access to the size and the pointer to the data I want to allocate and later to deallocate?
Just found out:
The version of OpenCV I'm using (2.3.1) throws an error when using cvSetMemoryManager. The reason is in its source code:
void cvSetMemoryManager( CvAllocFunc, CvFreeFunc, void * )
{
CV_Error( -1, "Custom memory allocator is not supported" );
}
I was very disappointed with this. I guess I can't use a custom memory pool with OpenCV anymore!
Right from the docs
http://opencv.willowgarage.com/documentation/c/core_utility_and_system_functions_and_macros.html#setmemorymanager
Use the
void cvSetMemoryManager(CvAllocFunc allocFunc=NULL, CvFreeFunc freeFunc=NULL, void* userdata=NULL)
function.
Your code
cvSetMemoryManager(allocCV(),deallocCV(),data);
is WRONG.
See what happens: you call allocCV and deallocCV functions (they return some pointer which is quietly converted to cvAllocFunc) !
And this is only the beginning. See the docs for alloc/dealloc semantics. You should write allocCV/deallocCV with correct signatures.
void* CV_CDECL allocCV(size_t size, void* userdata)
{
return ((YourMemPoolTypeWhichIDoNotKnow*)userdata)->POOLalloc(size);
}
int CV_CDECL deallocCV(void* pptr, void* userdata)
{
return ((YourMemPoolTypeWhichIDoNotKnow*)userdata)->POOLfree(pptr);
}
and then pass your MEMPOOL in the 'userdata' parameter:
cvSetMemoryManager(&allocCV, &deallocCV, (void*)MEMPOOL);
This is a standard way for a library to provide user callbacks.

Resources