javascript - Hyperledger Composer 检查数组
问题描述
我在我的 model.cto 文件中定义了一个数组Account[] family
,我想从我的 logic.js 中访问它。特别是,我只想在接收者在发送者的家庭数组中时才执行交易。
我的模型.cto:
namespace org.digitalpayment
asset Account identified by accountId {
o String accountId
--> Customer owner
o Double balance
}
participant Customer identified by customerId {
o String customerId
o String firstname
o String lastname
--> Account[] family optional
}
transaction AccountTransfer {
--> Account from
--> Account to
o Double amount
}
我的逻辑.js:
/**
* Account transaction
* @param {org.digitalpayment.AccountTransfer} accountTransfer
* @transaction
*/
async function accountTransfer(accountTransfer) {
if (accountTransfer.from.balance < accountTransfer.amount) {
throw new Error("Insufficient funds");
}
if (/*TODO check if the family array contains the receiver account*/) {
// perform transaction
accountTransfer.from.balance -= accountTransfer.amount;
accountTransfer.to.balance += accountTransfer.amount;
let assetRegistry = await getAssetRegistry('org.digitalpayment.Account');
await assetRegistry.update(accountTransfer.from);
await assetRegistry.update(accountTransfer.to);
} else {
throw new Error("Receiver is not part of the family");
}
}
解决方案
好的,所以基本上你想首先获取Family
资产的所有帐户,然后检查Customer
参与者是否包含在其中?如果我错了,请纠正我。一组合乎逻辑的步骤将是 -
- 检索
Account
基于to
和from
输入 - 使用变量
Customer
为每个检索每个Account
owner
- 获取
family
每个变量Customer
/**
* Account transaction
* @param {org.digitalpayment.AccountTransfer} accountTransfer
* @transaction
*/
async function accountTransfer(accountTransfer) {
if (accountTransfer.from.balance < accountTransfer.amount) {
throw new Error("Insufficient funds");
};
var from = accountTransfer.from;
var to = accountTransfer.to;
var fromCustomer = from.owner;
var toCustomer = to.owner;
var fromCustomerFamily = fromCustomer.family;
if (fromCustomerFamily && fromCustomerFamily.includes(to)) {
// perform transaction
accountTransfer.from.balance -= accountTransfer.amount;
accountTransfer.to.balance += accountTransfer.amount;
let assetRegistry = await getAssetRegistry('org.digitalpayment.Account');
await assetRegistry.update(accountTransfer.from);
await assetRegistry.update(accountTransfer.to);
} else {
throw new Error("Receiver is not part of the family");
}
}
由于最近几个Composer
版本的语法更改可能无法正常工作,具体取决于您在项目中使用的版本。如果这不起作用并且您使用的是旧版本,请告诉我,我会相应地更新答案。
推荐阅读
- arrays - AssemblyScript 数组访问导致内存越界
- python - 正则表达式捕获具有不明确逻辑 OR 的组
- android - 房间迁移未找到表格列
- algorithm - 是否有一个散列函数以一种独特的方式将两个整数映射到一个整数?
- python - 如何在 Python 中使用 Selenium 和 BeautifulSoup4 抓取多个 URL
- c - 将目录的路径传递给函数,C语言
- tensorflow - 不使用 GPU 的 Tensorflow.js 示例
- java - 如何在 Android 中读取 Firebase 用户数据
- c# - C# RemoveBG API
- reactjs - 无法读取 setTimeOut 内的属性,我该如何解决?