Trying to get array of phone:balance but got latest value, and balance:balance - string

import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
import "#openzeppelin/contracts/utils/Strings.sol";
contract GoTekERC721 is ERC721, Ownable {
constructor() ERC721("Go NFT", "GoN") {}
//Owner to Phone
mapping(address => uint256[]) public phones;
//change
// Phone to Balance
mapping(uint256 => uint256) public balance;
//mapping(uint256 => uint256) public userBalances;
function register(uint256 phone, uint256 Balance) public {
_mint(msg.sender, phone);
phones[msg.sender].push(phone);
balance[phone] = Balance;
}
function details(address owner) public view returns(string memory) {
uint256[] memory ownerPhones = phones[owner];
string memory var1;
string memory var2;
for (uint256 i = 0; i < ownerPhones.length; i++) {
uint256 phone = ownerPhones[i];
mapping(uint256 => uint256) storage userBalances=balance;
var1=Strings.toString(userBalances[phone]);
var2=Strings.toString(balance[phone]);
}
return string(bytes.concat(bytes(var1),":",bytes(var2)));
}
}
I'm trying to get details output 9658965896:199, 8569856985:49, but I get latest value of balance 199:199 or 49:49 not in array also ...
How can I fix it?

Related

solidity smart contract function

I have a simple NFT contract and trying to extract the number of tokens using _tokenIds.current(); but after deployment I call the function and it gives me this : BN { negative: 0, words: [ 0, <1 empty item> ], length: 1, red: null } while I am expecting a uint 256.
this is the contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
import "#openzeppelin/contracts/utils/Counters.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
//should I add payable here????
contract Main_NFT_contract is ERC721, Ownable {
using Counters for Counters.Counter;
using Strings for uint256;
Counters.Counter private _tokenIds;
mapping(uint256 => string) private _tokenURIs;
constructor() ERC721("NFE collection", "N*F*E") {}
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
_tokenURIs[tokenId] = _tokenURI;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
return _tokenURI;
}
function mint(address recipient, string memory uri)
public
onlyOwner
returns (uint256)
{
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(recipient, newItemId);
_setTokenURI(newItemId, uri);
return newItemId;
}
function burn (uint256 tokenId)
public
onlyOwner
{
_burn(tokenId);
}
function NumberOfTokens()
public
view
returns (uint256)
{
uint256 num_token = _tokenIds.current();
return num_token;
}

Chosing identies for DDD based journaling system

Related to this question, I am modelling the identities for a trade logging/management system.
It will be multi-tenanted with users only able to see tenants they have been given rights to, so I have a partition key called TenantId.
The other fields are as follows for a Trade that has taken place:
internal class Trade : ValueObject
{
public Account Account { get; init; } // See below - belongs to a Tenant / Account / Broker
public TradeId TradeId { get; init; } // Unique tradeId (string i.e. 0000d695.234242.01.01)
public UserId UserId { get; init; } // A user potentially could create trades in other tenants, with appropriate claims/roles as part of an access control context.
public Contract Contract { get; init; } // Exact same contract can be traded on many different brokers
public string Exchange { get; init; }
public string BrokerContractId { get; init; }
public string BucketName { get; init; }
public decimal Position { get; init; }
public double Average { get; init; }
public DateTime Timestamp { get; init; }
protected override IEnumerable<object> GetEqualityComponents()
{
yield return Account;
yield return TradeId;
}
}
I don't see a trade as an entity as such, as there are no operations to perform - it is merely a log entry. I use the following identities to identify it:
public class TradeId : Identity
{
public TradeId(string fillId) : base(fillId) { } // Must be unique for each and every fill.
}
public class UserId : Identity
{
public UserId(string username) : base(username) { }
}
I have an account, which is unique to a broker, and coupled strongly as part of a tenant (one tenant would never see anothers brokerage account):
public class AccountId : Identity
{
public AccountId(string accountNumber) : base(accountNumber) { }
}
// An account belongs to broker, and within a tenant (that can have multiple accounts).
public class Account : EntityWithCompositeId
{
public AccountId AccountId { get; init; }
public TenantId TenantId { get; init; }
public BrokerId BrokerId { get; init; }
public Account(TenantId tenantId, BrokerId brokerId, AccountId accountId)
{
TenantId = tenantId;
BrokerId = brokerId;
AccountId = accountId;
}
protected override IEnumerable<object> GetIdentityComponents()
{
yield return TenantId;
yield return BrokerId;
yield return AccountId;
}
}
Question 1: I have noticed that if TenantId is part of the AccountId (since an account cannot exist without the Tenant), it would save me adding TenantId in all my entitities - are there any disadvantages to this?
Question 2: Given the below contract, even if i did include unique data such as FIGI composite ID, regardless of it being unique, it is still a value object as it wouldn't ever have business logic inside - is this the right school of thought?
// The same contract can exist on more than one broker.
public class Contract : ValueObject
{
public string Symbol { get; init; }
public string Currency { get; init; }
public override string ToString() => Symbol;
protected override IEnumerable<object> GetEqualityComponents()
{
yield return Symbol;
yield return Currency;
}
}
I have started to flesh this out, an AccountID is ok as the three components form the identity:
// An account belongs to broker, and within a tenant (that can have multiple accounts).
public class AccountId : ValueObject
{
public string Id { get; init; }
public TenantId TenantId { get; init; }
public BrokerId BrokerId { get; init; }
public AccountId(TenantId tenantId, BrokerId brokerId, string id)
{
TenantId = tenantId;
BrokerId = brokerId;
Id = id;
}
protected override IEnumerable<object> GetEqualityComponents()
{
yield return TenantId;
yield return BrokerId;
yield return Id;
}
}
Executions are value objects, with no lifetime as they cannot exist outside of an account:
public class FillDetail : ValueObject
{
public string FillId { get; init; }
// Must be unique for each and every fill.
public FillDetail(string fillId) => FillId = fillId;
protected override IEnumerable<object> GetEqualityComponents()
{
yield return FillId;
}
}
public class Execution : ValueObject
{
public FillDetail FillDetail { get; init; }
public UserId UserId { get; init; } // A user potentially could create trades in other tenants, with appropriate claims/roles.
public Contract Contract { get; init; }
public string Exchange { get; init; }
public string BrokerContractId { get; init; }
public string BucketName { get; init; }
public decimal Size { get; init; }
public double Price { get; init; } // The execution price, excluding commissions.
public DateTime Timestamp { get; init; }
public Action Action { get; init; }
public bool IsForcedLiquidation { get; init; }
public Side Side { get; init; }
public Liquidity Liquidity { get; init; }
public FillDetail? Correction { get; init; }
protected override IEnumerable<object> GetEqualityComponents()
{
yield return FillDetail;
yield return UserId;
yield return Contract;
yield return Exchange;
yield return BrokerContractId;
yield return BucketName;
yield return Size;
yield return Price;
yield return Timestamp;
yield return Action;
yield return IsForcedLiquidation;
yield return Side;
yield return Liquidity;
if (Correction != null) yield return Correction;
}
}
The account is a Entity as it evolves over time, and would have business logic to for example:
Calculate P+L when executions are entered on the ledger
Prevent trades from taking place if current positions (derived from the execution log) are open, or additional orders, hedges etc.
This logic would belong in the Account:
public sealed class Account : Entity
{
public AccountId AccountId { get; init; }
readonly List<Execution> executions = new();
public void LogExecution(Execution execution)
{
// TODO: Check if this execution already exists, if so ignore it.
this.executions.Add(execution);
// This is where we would scan list of prior trades, calculate open positions, P+L etc.
}
public void PlaceOrder(Contract contract)
{
// We could have limit of no more than 10% of account balance allocated to any one position.
}
public IEnumerable<Execution> GetExecutions()
{
throw new NotImplementedException();
}
protected override IEnumerable<ValueObject> GetIdentityComponents()
{
yield return AccountId;
}
}
I think this is more likely a better model, whilst I now have concerns on the massive execution log (and managing that performance) however I will save that for a further question.
Feel free to provide your own answers, pointers much appreciated.

Sending value from escrow contract address with transfer function

I want to call transferMoney() function which should send value (requests[_id].value) to an address address(uint160(requests[_id].provider)) with the transfer function of solidity. When I call this function via my DApp-Frontend using MetaMask, first I get the confirmation but the transaction gots reverted by the EVM. On etherscan, I see the status = fail. My aim is to send value from contract owner to another account.
What could cause the problem?
Here is the transaction hash on etherscan ropsten testnet: 0x30cef6bc33a25aeb4693a7c463ddf5dd597e0bd2c2ceb47feb38f29599feb4aa
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.21 <0.7.0;
contract PrinterMarketplace {
uint256 public requestCount = 0;
uint balance;
address payable escrow = msg.sender;
mapping(uint256 => Request) public requests;
struct Request {
uint256 id;
string fileName;
string fileHash;
address payable client;
address payable provider;
string price;
uint256 value;
string status;
}
function purchaseOffer(
uint256 _id,
address payable _client,
address payable _provider,
string memory _fileHash
) public payable{
requests[_id].status = "purchased";
requests[_id].value = msg.value;
emit OrderEvent(_id, _fileHash, _client, _provider, requests[_id].status);
escrow.transfer(msg.value);
}
function transferMoney(
uint256 _id
) public {
address(uint160(requests[_id].provider)).transfer(requests[_id].value);
requests[_id].status = "paid";
}
}

structuremap object reference with particular dependency

I am new to structuremap.
I want to get Shopper classes object with either "master" or "visa" dependency based on user input.
In below code I have created two concrete classes MasterCard and Visa from ICreditCard. I am injecting dependency of ICreditCard but when code is executing based on user's option I want to inject MasterCard or Visa depdency to Shopper class and get reference of that Shopper class object.
Can someone tell me how to do it if it is possible. I also want to know if I want to initialise object in some other class then how to do it(is it by exposing a method returning container object?)
class Program
{
static void Main(string[] args)
{
var container = new Container();
container.Configure(c => c.For<ICreditCard>().Use<MasterCard>().Named("master"));
container.Configure(x => x.For<ICreditCard>().Use<Visa>().Named("visa"));
//how to get instance of Shopper with master card object reference?
Console.ReadKey();
}
public class Visa : ICreditCard
{
public string Charge()
{
return "Visa... Visa";
}
public int ChargeCount
{
get { return 0; }
}
}
public class MasterCard : ICreditCard
{
public string Charge()
{
ChargeCount++;
return "Charging with the MasterCard!";
}
public int ChargeCount { get; set; }
}
public interface ICreditCard
{
string Charge();
int ChargeCount { get; }
}
public class Shopper
{
private readonly ICreditCard creditCard;
public Shopper(ICreditCard creditCard)
{
this.creditCard = creditCard;
}
public int ChargesForCurrentCard
{
get { return creditCard.ChargeCount; }
}
public void Charge()
{
Console.WriteLine(creditCard.Charge());
}
}
}

AutoMapper resolver not passing expected type

Given the following classes and resolver, why am I getting this error? I don't see why ProductAddModel is being passed in at all.
AutoMapper.AutoMapperMappingException was unhandled by user code
Message=Value supplied is of type System.Decimal but expected
AuctionCMS.Framework.Models.Admin.ProductAddModel. Change the value
resolver source type, or redirect the source value supplied to the
value resolver using FromMember.
Types:
public class Currency
{
public Int64 Value { get; set; }
// Spot saved for currency type and any other extra properties
}
public class Product
{
public Currency Price { get; set; }
public Currency ReservePrice { get; set; }
}
public class ProductAddModel
{
public Decimal Price { get; set; }
public Decimal ReservePrice { get; set; }
}
Resolver code:
public class DecimalToCurrencyValueResolver : ValueResolver<decimal, Currency>
{
#region Overrides of ValueResolver<decimal,Currency>
protected override Currency ResolveCore(decimal source)
{
return new Currency() { Value = (Int64)((decimal)source) * 1000 };
}
#endregion
}
public class CurrencyToDecimalValueResolver : ValueResolver<Currency, decimal>
{
#region Overrides of ValueResolver<decimal,Currency>
protected override decimal ResolveCore(Currency source)
{
return (decimal)source.Value * 1000;
}
Mapping code:
Mapper.CreateMap<ProductAddModel, Product>()
.ForMember(x => x.Price, opt => opt.ResolveUsing<DecimalToCurrencyValueResolver>())
.ForMember(x => x.ReservePrice, opt => opt.ResolveUsing<DecimalToCurrencyValueResolver>());
Mapper.CreateMap<Product, ProductAddModel>()
.ForMember(x => x.Price, opt => opt.ResolveUsing<CurrencyToDecimalValueResolver>())
.ForMember(x => x.ReservePrice, opt => opt.ResolveUsing<CurrencyToDecimalValueResolver>());
var model = new ProductAddModel();
var product = new Product();
Mapper.Map<ProductAddModel, Product>(model, product);
What am I doing wrong and is this approach the best way to handle simple transforms during the mapping process?
Thanks!
Use TypeConverters instead:
public class CurrencyToDecimalTypeConverter : ITypeConverter<Currency, Decimal>
{
public decimal Convert(ResolutionContext context)
{
return ((Currency)context.SourceValue).Value * 1000;
}
}
public class DecimalToCurrencyTypeConverter : ITypeConverter<Decimal, Currency>
{
public Currency Convert(ResolutionContext context)
{
return new Currency() { Value = (Int64)((decimal)context.SourceValue) * 1000 };
}
}
Here is configuration:
Mapper.CreateMap<ProductAddModel, Product>();
Mapper.CreateMap<Product, ProductAddModel>();
Mapper.CreateMap<Decimal, Currency>().ConvertUsing<DecimalToCurrencyTypeConverter>();
Mapper.CreateMap<Currency, Decimal>().ConvertUsing<CurrencyToDecimalTypeConverter>();
var model = new ProductAddModel();
var product = new Product();
Mapper.Map<ProductAddModel, Product>(model, product);
In resolver decimal is used and in mapping productAddModel is passed. So mapping should be like this
Mapper.CreateMap<ProductAddModel, Product>()
.ForMember(x => x.Price, opt => opt.ResolveUsing<DecimalToCurrencyValueResolver>().FromMember(e => e.Value ));

Resources