Skip to content

Commit 30bcf3a

Browse files
committed
feat: mergeTx function for Forest
Signed-off-by: MASDXI <sirawitt42@gmail.com>
1 parent 1dc623d commit 30bcf3a

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

contracts/libraries/Forest.sol

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ library Forest {
3535
* @param from The spender of the transaction.
3636
*/
3737
event TransactionCreated(bytes32 indexed root, bytes32 id, address indexed from);
38-
38+
3939
/**
4040
* @notice Event emitted when a transaction is spent.
4141
* @param id The identifier of the transaction.
@@ -58,6 +58,11 @@ library Forest {
5858
*/
5959
error TransactionZeroValue();
6060

61+
/**
62+
* @notice Error thrown when trying to merge over 255 transactions.
63+
*/
64+
error TransactionMergeSizeExceed();
65+
6166
/**
6267
* @notice Error thrown when the spending value exceeds the transaction value.
6368
* @param value The value of the transaction.
@@ -141,7 +146,27 @@ library Forest {
141146
/**
142147
* @notice not suitable for use in production.
143148
*/
144-
function mergeTx(DAG storage self, bytes32 [] memory ids) internal {
145-
// @TODO
149+
function mergeTx(DAG storage self, bytes32[] memory ids) internal {
150+
uint256 length = ids.length;
151+
if (length >= type(uint8).max) revert TransactionMergeSizeExceed();
152+
Tx memory ptr = getTx(self, ids[0]);
153+
if (msg.sender != ptr.owner) revert TransactionUnauthorized();
154+
Tx memory txn;
155+
unchecked {
156+
for (uint8 index = 1; index < ids.length; index++) {
157+
txn = getTx(self, ids[index]);
158+
if (ptr.root == txn.root && ptr.owner == txn.owner) {
159+
self.txs[ids[index]].value = 0;
160+
ptr.value += txn.value;
161+
if (ptr.level < txn.level) {
162+
ptr.level = txn.level;
163+
}
164+
}
165+
}
166+
createTx(self, ptr, ptr.owner);
167+
if (ptr.level > self.hierarchy[ids[0]]) {
168+
self.hierarchy[ids[0]] = ptr.level;
169+
}
170+
}
146171
}
147172
}

0 commit comments

Comments
 (0)