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

交易发起方预提交(preCommitSend)

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

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

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

/*
 * preCommitSend is the first step of two-phase commit cross-chain transaction process, it will be executed on the client side and lock the related assets/data
 * In this example, this function transfer X units from client's local
 * account(first arg) to remote account(second 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) preCommitSend(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[0]
	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)
}

相关文档