更新时间:2021-12-30 GMT+08:00
分享

交易接收方预提交(preCommitRecv)

该方法用于在跨链资产交换接收方所属区块链上执行预提交操作,即修改接收方所属区块链上对应资产的值,并对该资产上锁。

本例中,该方法将修改接收方所属区块链上args[1]对应账户的余额为跨链资产交换完成后的数值,同时对该账户上锁,并在数据锁中保存跨链资产交换发生前该账户的余额。putStateWithLock方法的实现请参考修改跨链资产数值(putStateWithLock)

该方法为必选方法,需在智能合约中以相同命名定义该方法,否则将导致跨链资产交换失败。

/*
 * preCommitRecv is the second step of two-phase cross-chain transaction process, it will be executed on the server side and lock the related assets/data
 * In this example, this function will make local account(second arg) received
 * X units transferred by remote account(first arg) and lock the local account
 * The example args[] is {"a","b","1","txid123"}
 * @Param args[0]: The name of the account on blockchain A that will transfer the amount of units to the account on blockchain B
 * @Param args[1]: The name of the account on blockchain B that will receive the amount of units from the account on blockchainA
 * @Param args[2]: The amount of unit that will be transferred from args[0](account on blockchain A) to args[1](account on blockchain B)
 * @Param args[3]: The id of this transaction that transfer units of one account to another account
 */
func (t *TCSExampleChaincode) preCommitRecv(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	if len(args) != 4 {
		return shim.Error("Incorrect number of arguments. Expecting 4")
	}
        txID := args[3]
	// Get account balance from blockchain
	account := args[1]
	balanceBytes, err := stub.GetState(account)
	if err != nil {
		return shim.Error(err.Error())
	}
	if balanceBytes == nil {
		return shim.Error("account not found: " + account)
	}
	balance, err := strconv.Atoi(string(balanceBytes))
	if err != nil {
		return shim.Error(err.Error())
	}
	// Get transfer amount from args
	amount, err := strconv.Atoi(args[2])
	if err != nil {
		return shim.Error(err.Error())
	}
	// Execute the business process
	balance = balance + amount
	// Use specific function to put state for cross-chain transaction
	err = putStateWithLock(stub, txID, account, []byte(strconv.Itoa(balance)))
	if err != nil {
		return shim.Error(err.Error())
	}
	return shim.Success(nil)
}
分享:

    相关文档

    相关产品