Generate Receipt in Smart Contract
Feature
Receipt is used to prove or remind the occurrence of certain operations, a typical application is to record a transfer from A to B with additional memo.
Smart contract can generate receipt by invoking the system function blockchain.receipt
offered by blockchain infrastructure.
Receipt is stored in block data associated with a transaction, which of course will be verified by all nodes in blockchain network.
Remember that receipt can not be queried within a contract, one can only query receipt by parsing block datas or
requesting receipt by a transaction hash through rpc interfaces.
Receipt is much more cheaper than contract storage. It only costs gas, different from contract storage which costs both gas and ram.
Generate Receipt
Smart contract generates receipt by invoking the system function blockchain.receipt
.
Here is an example, when the receiptf function of this contract is called, three receipts will be generated.
class Contract {
init() {
}
receiptf() {
blockchain.receipt(JSON.stringify(["from", "to", "100.01"]));
blockchain.receipt('{"name": "Cindy", "amount": 1000}');
blockchain.receipt("transfer accepted");
}
}
module.exports = Contract;
blockchain.receipt
accept a string parameter, which refers to the content of the receipt, and has no returns.
An runtime error will be thrown if it's not executed successfully, which should not happen under normal circumstances.
We strongly recommend developers to use json format string as the content, which is convenient for subsequent parsing.
The generated receipt also contains the contract name and action name indicating which method is responsible to the receipt. The three receipt generated above will look like:
# first
{"funcName":"ContractFhx828oUPYHRtkp9ABaBFHwm6S94eeeai1TD3FkTgLMz/receiptf", "content":"[\"from\",\"to\",\"100.01\"]"}
# second
{"funcName":"ContractFhx828oUPYHRtkp9ABaBFHwm6S94eeeai1TD3FkTgLMz/receiptf", "content":"{\"name\": \"Cindy\", \"amount\": 1000}"}
# third
{"funcName":"ContractFhx828oUPYHRtkp9ABaBFHwm6S94eeeai1TD3FkTgLMz/receiptf", "content":"transfer accepted"}
ContractFhx828oUPYHRtkp9ABaBFHwm6S94eeeai1TD3FkTgLM
is ID of this contract.
Query Receipt
Query Receipt by transaction hash
The receipt generated by a specific transaction can be queried with transaction hash through rpc interfaces.
Please refer to /getTxReceiptByHash
Query Receipt by block data
A complete block data contains all the transactions and the corresponding receipts, one can download the block data and parse to get all the receipts generated in this block.
Please refer to /getBlockByHash and /getBlockByNumber
and set the complete
in the request parameters as true