Identification of purchased product - blockchain

I have created coins on test network.Now the confusion is,
I have distributed coins to 100 members,who can use those coins to buy digital products(domains) on my platform.Now the confusion is if all domains are listed for sale for $10(100 coins),and multiple domains got sold,how can I identify which user made payment to me.Because all users can see my wallet address.Is there any way to detect that payment came in for which purchased product?

Make your wallet into a smart contract.
Then checkout the fallback function payable. That function gets called anytime someone sends ether to your contract.
function () payable {
address guyWhoPaiedMe = msg.sender;
}
To figure out who sent you the ether use msg.sender.

You can pass the identifier of a particular product as the input data of the transaction. In this case it will be easy to identify the product against which the payment was made.
web3.eth.sendTransaction
web3.eth.sendTransaction(transactionObject [, callback])
Sends a transaction to the network.
Parameters
1. Object - The transaction object to send:
• from: String - The address for the sending account. Uses the web3.eth.defaultAccount property, if not specified.
• to: String - (optional) The destination address of the message, left undefined for a contract-creation transaction.
• value: Number|String|BigNumber - (optional) The value transferred for the transaction in Wei, also the endowment if it's a contract-creation transaction.
• gas: Number|String|BigNumber - (optional, default: To-Be-Determined) The amount of gas to use for the transaction (unused gas is refunded).
• gasPrice: Number|String|BigNumber - (optional, default: To-Be-Determined) The price of gas for this transaction in wei, defaults to the mean network gas price.
• data: String - (optional) Either a byte string containing the associated data of the message, or in the case of a contract-creation transaction, the initialisation code.
• nonce: Number - (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce.
2. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.
Returns
String - The 32 Bytes transaction hash as HEX string.

Related

I want to create a nft as a hotel room ticket. Is it possible?

I am a PHP user but a complete novice in blockchain.
I want to create a nft as a hotel room ticket.
I would like to sell them on platforms such as opensensea.
Is it realistically possible to implement the following?
1: Can only be used once.
2: It has an expiration date.
3: After use, the design of the nft will change for used.
4: If holder don't use it and the expiration date has passed, the design will change to used.
From my research, it seems that the "expiration date" can be implemented.
What I find problematic is
3: "After use, the nft design will change to used".
I'm not sure how to do this automatically, so I'd prefer to do it manually.
For example, is it possible to manually rewrite the data of nft "A" to "used" when the holder of nft "A" makes a hotel reservation?
I would appreciate any advice you can give me.
Thank you.
Of course, it's possible.
OpenSea extracts the NFT's metadata from the url returns by the tokenURI function of the NFT smart contract. So you can achieve the goal by overriding this function.
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
//Implement the features you want to add
//Imagine there is already structure called TicketInfo that stores information of NFTs and "used" NFT has zero index in the collection
uint256 tokenId = _tokenId;
TicketInfo storage ticket = ticketInfo[tokenId];
if(ticket.expirationDate < now || ticket.isUsed) tokenId = 0;
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}

Make a Solana program pay for the transaction

I'm not sure that is possible, but what I would like to do is to make the program pay for the transaction cost and make the user use the program for free.
In my mind the process would be:
I send some Solana to the account of the program to handle future transactions.
A user interact with the function SaveData
(Inside this function in the future will be some sort of mechanism to check if the user can interact with the function without paying)
The program would pay for the transaction, so the user don't have to pay even a single Lamport.
My code is:
#[derive(Accounts)]
pub struct SaveData<'info> {
#[account(init, payer = system_program, space = 8 + 50 + 32 )]
pub data_account: Account<'info, DataState>,
#[account(mut)]
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[account]
pub struct DataState {
pub authority: Pubkey,
content: String
}
I tried setting system_program as the payer, but if I try to build the program with anchor it gives me this error:
error[E0599]: no method named `exit` found for struct `SaveData` in the current scope
--> programs/test-smart-contract/src/lib.rs:5:1
|
5 | #[program]
| ^^^^^^^^^^ method not found in `SaveData<'_>`
...
61 | pub struct SaveData<'info> {
| -------------------------- method `exit` not found for this
How can I achieve what I want to do?
Update
In order to manage this problem, I started developing this service: cowsigner.com
Unfortunately every transaction has a fee payer which is specified and needs to sign on the transaction and be a signer account.
System program is a native program on Solana and you're misusing it in your case. This is the official definition for it:
Create new accounts, allocate account data, assign accounts to owning programs, transfer lamports from System Program owned accounts and pay transaction fees.
If you wish to pay for the fees then you would need a dedicated account, that is specified as the feePayer on each transaction and signs on each transaction as well.

DDD - Concurrency with quantity

Hi everyone,
I'm a little bit lost with a problem thinking in ddd way.
Imagine you have an application to sell concert ticket. So you have an entity which is called Concert with the quantity number and a method to buy a ticket.
class Concert {
constructor(
public id: string,
public name: string,
public ticketQuantity: number,
) {}
buyTicket() {
this.ticketQuantity = this.ticketQuantity - 1;
}
}
The command looks like this:
async execute(command: BookConcertCommand): Promise<void> {
const concert = await this.concertRepository.findById(command.concertId);
concert.buyTicket();
await this.concertRepository.save(concert);
}
Imagine, your application has to carry a lot of users and 1000 users try to buy a ticket at the same when the ticketQuantity is 500.
How can you ensure the invariant of the quantity can't be lower than 0 ?
How can you deal with concurrency here because even if two users try to buy a ticket at the same time the data can be false ?
What are the patterns we can use to ensure consistency and concurrency ?
Optimistic or pessismistic concurrency can't be a solution because it will frustrate a lot of users and we try to put all our logic domain into our domain so we can't put any logic inside sql/db or use a transactional script approach.
How can you ensure the invariant of the quantity can't be lower than 0
You include logic in your domain model that only assigns a ticket if at least one unassigned ticket is available.
You include locking (either optimistic or pessimistic) to ensure "first writer wins" -- the loser(s) in a data race should abort or retry.
If your book of record was just data in memory, then you would ensure that all attempts to buy tickets for concert 12345 must first acquire the same lock. In effect, you serialize the requests so that the business logic is running one at a time only.
If your book of record was a relational database, then within the context of each transaction you might perform a "select for update" to get a copy of the current data, and perform the update in the same transaction. The database will raise it's flavor of concurrent modification exception to the connections that lose the race.
Alternatively, you use something like the semantics of a conditional-write / compare and swap: you get an unlocked copy of the concert from the book of record, make your changes, then send a "update this record if it still looks like the unlocked copy" message, if you get the response announcing you've won the race, congratulations - you're done. If not, you retry or fail.
Optimistic or pessismistic concurrency can't be a solution because it will frustrate a lot of users
Of course it can
If the concert is overbooked, they are going to be frustrated anyway
The business logic doesn't have to run synchronously with the request - it might be acceptable to write down that they want a ticket, and then contact them asynchronously to let them know that a ticket has been assigned to them
It may be helpful to review some of Udi Dahan's writing on collaborative and competitive domains; for instance, this piece from 2011.
In a collaborative domain, an inherent property of the domain is that multiple actors operate in parallel on the same set of data. A reservation system for concerts would be a good example of a collaborative domain – everyone wants the “good seats” (although it might be better call that competitive rather than collaborative, it is effectively the same principle).
You might be following these steps:
1- ReserveRequested -> ReserveRequestAccepted -> TicketReserved
2- ReserveRequested -> ReserveRequestRejected
When somebody clicks on the buy ticket button, you should create a reserve request entity, and then you can process the reservation in the background and by a queue system.
On the user side, you can return a unique reserve request-id to check the result of the process. So the frontend developer should fetch the result of process periodically until it succeeds or fails.

How to manually burn tokens on BSC network

I have a token contract deployed on Binance Smart Chain and want to burn some of the tokens manualy, thus to execute following function call from some kind of console.
myContract.burn(10000);
I have ABI and bytecode
How and where can I execute this?
If the burn() function has a public or external visibility modifier, you can execute it by submitting a transaction containing the function signature and the argument value(s) in the data field.
One of the ways is to build the data field value manually or semi-manually
const data = web3.eth.abi.encodeFunctionCall({
name: 'burn',
type: 'function',
inputs: [{
type: 'uint256',
name: '_amount'
}]
}, [10000]);
which returns
0x42966c680000000000000000000000000000000000000000000000000000000000002710
42966c68 is the function signature
2710 is hex value for 10000 (dec)
and pass it to any wallet that supports custom data field (e.g. MyEtherWallet).
Another way is to instantiate your contract with web3.eth.Contract and execute the function from there. This generates the data field for you and if you've configured your web3 instance correctly, it also uses your private key to sign the transaction and broadcasts it to the network.
const contract = new web3.eth.Contract(jsonInterface, contractAddress);
contract.methods.burn(10000).send({from: yourAddress});

gas required exceeds allowance or always failing transaction on Geth private blockchain but works fine in others

I have created a private blockchain using geth. I also have a contract in which there is a function which call another function it third contract to set an address. I can call this function on Local blockchains like testRPC and Ganache blockchain, Even it works in TestNet. But Once I setup the private blockchain using (geth). I get this error:
Gas estimation errored with the following message (see below).
The transaction execution will likely fail. Do you want to force sending?
gas required exceeds allowance or always failing transaction
I have enough ETH in the caller account and also
I have enough ETH in the caller account and also
GasLimit is high enough
The functions does not have any loop or fancy operation, setting an address and some condition checks
The node is an Ubuntu 16.04
geth -v --> 1.8.12-stable
// in contract 1
function func(address addr) public returns (bool result) {
Cantract2 c = Cantract2(addr);
if (!c.setAddress(..)) {
return false;
}
.....
return true;
}
You might want to check the genesis file/chain specification of your private test chain.
There is a variable called block gas limit that affects how much gas you can spend on each block. I recall that the default value used to be very low back in the days and maybe you are using such a config. What you could do:
check the block gas limit in the dev chain configuration and increase it as to your needs
or let the local test chain run for some time as the client will vote up the default block gas limit slowly, allowing you for larger transactions per block