Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add method to hash TX on TransactionRequest classes #1485

Merged
merged 34 commits into from
Dec 13, 2023
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
cbaaeeb
remove provider and transaction from hasher package
Torres-ssf Dec 7, 2023
9c94e09
remove hashTransaction from hasher
Torres-ssf Dec 7, 2023
d240646
implement hashTransaction on providers package
Torres-ssf Dec 7, 2023
5c13a73
adding fixture
Torres-ssf Dec 7, 2023
bd67fd1
add method getTransactionId to baseTransactionRequest
Torres-ssf Dec 7, 2023
e0d8870
implementing getTransactionId on transaction request classes
Torres-ssf Dec 7, 2023
91afaaf
add hasher package to providers
Torres-ssf Dec 7, 2023
7198612
hashing tx directly from request
Torres-ssf Dec 7, 2023
ae55105
add changeset
Torres-ssf Dec 7, 2023
40d5110
using private instead of #
Torres-ssf Dec 7, 2023
7809d27
implement createTransfer on account class
Torres-ssf Dec 7, 2023
c456a60
add test for Account createTransfer
Torres-ssf Dec 7, 2023
4f0fd7c
add createTransfer on predicate class
Torres-ssf Dec 7, 2023
6356a90
updating docs
Torres-ssf Dec 7, 2023
9b6e986
remove TODO
Torres-ssf Dec 8, 2023
89b6704
Merge branch 'master' into st/feat/hash-tx-on-transaction-request
Torres-ssf Dec 8, 2023
1ca9d0c
Re-triggering workflow
Torres-ssf Dec 8, 2023
bd9220f
Merge branch 'master' into st/feat/hash-tx-on-transaction-request
Torres-ssf Dec 10, 2023
13e4e58
Merge branch 'master' into st/feat/hash-tx-on-transaction-request
arboleya Dec 11, 2023
54ef0a8
Merge branch 'master' into st/feat/hash-tx-on-transaction-request
arboleya Dec 11, 2023
84bd31e
Merge branch 'master' into st/feat/hash-tx-on-transaction-request
Torres-ssf Dec 11, 2023
956749e
Merge branch 'master' into st/feat/hash-tx-on-transaction-request
danielbate Dec 11, 2023
252dac1
Merge branch 'master' into st/feat/hash-tx-on-transaction-request
danielbate Dec 11, 2023
d923865
add doc block
Torres-ssf Dec 12, 2023
9c0b6da
Merge branch 'master' into st/feat/hash-tx-on-transaction-request
Torres-ssf Dec 12, 2023
7a7e67f
moving page transfering assets to cookbook section
Torres-ssf Dec 12, 2023
6d64bf3
Merge branch 'st/feat/hash-tx-on-transaction-request' of github.com:F…
Torres-ssf Dec 12, 2023
95dda6d
improving doc page Asset Transfers
Torres-ssf Dec 12, 2023
dc9e3e5
Merge branch 'master' into st/feat/hash-tx-on-transaction-request
danielbate Dec 12, 2023
6a49d7d
re-triggering workflow
Torres-ssf Dec 12, 2023
d9b48d6
Merge branch 'master' into st/feat/hash-tx-on-transaction-request
Torres-ssf Dec 12, 2023
d03a65a
Merge branch 'master' into st/feat/hash-tx-on-transaction-request
Torres-ssf Dec 13, 2023
74fbc98
Merge branch 'master' into st/feat/hash-tx-on-transaction-request
Torres-ssf Dec 13, 2023
492c5d8
Merge branch 'master' into st/feat/hash-tx-on-transaction-request
Torres-ssf Dec 13, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/brown-zebras-remember.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@fuel-ts/hasher": minor
"@fuel-ts/program": minor
"@fuel-ts/providers": minor
"@fuel-ts/wallet": minor
---

add method to hash tx on TransactionRequest classes
Original file line number Diff line number Diff line change
@@ -1,41 +1,38 @@
import { safeExec } from '@fuel-ts/errors/test-utils';
import type { Provider } from 'fuels';
import { WalletUnlocked, Predicate, BN, getRandomB256, BaseAssetId } from 'fuels';

import {
WalletUnlocked,
FUEL_NETWORK_URL,
Provider,
Predicate,
BN,
getRandomB256,
BaseAssetId,
} from 'fuels';

import { DocSnippetProjectsEnum, getDocsSnippetsForcProject } from '../../../test/fixtures/forc-projects';
DocSnippetProjectsEnum,
getDocsSnippetsForcProject,
} from '../../../test/fixtures/forc-projects';
import { getTestWallet } from '../../utils';

describe(__filename, () => {
let walletWithFunds: WalletUnlocked;
let provider: Provider;
let gasPrice: BN;
const { abiContents: abi, binHexlified: bin } = getDocsSnippetsForcProject(
DocSnippetProjectsEnum.SIMPLE_PREDICATE
);

beforeAll(async () => {
walletWithFunds = await getTestWallet();
({ minGasPrice: gasPrice } = walletWithFunds.provider.getGasConfig());
provider = walletWithFunds.provider;
({ minGasPrice: gasPrice } = provider.getGasConfig());
});

it('should successfully use predicate to spend assets', async () => {
// #region send-and-spend-funds-from-predicates-2
const provider = await Provider.create(FUEL_NETWORK_URL);
const predicate = new Predicate(bin, provider, abi);
// #endregion send-and-spend-funds-from-predicates-2

// #region send-and-spend-funds-from-predicates-3
const amountToPredicate = 300_000;
const amountToPredicate = 10_000;

const tx = await walletWithFunds.transfer(predicate.address, amountToPredicate, BaseAssetId, {
gasPrice,
gasLimit: 10_000,
gasLimit: 1_000,
});

await tx.waitForResult();
Expand All @@ -58,11 +55,11 @@ describe(__filename, () => {

const tx2 = await predicate.transfer(
receiverWallet.address,
amountToPredicate - 150_000,
amountToPredicate - 1000,
BaseAssetId,
{
gasPrice,
gasLimit: 10_000,
gasLimit: 1_000,
}
);

Expand All @@ -71,14 +68,13 @@ describe(__filename, () => {
});

it('should fail when trying to spend predicates entire amount', async () => {
const provider = await Provider.create(FUEL_NETWORK_URL);
const predicate = new Predicate(bin, provider, abi);

const amountToPredicate = 100;

const tx = await walletWithFunds.transfer(predicate.address, amountToPredicate, BaseAssetId, {
gasPrice,
gasLimit: 10_000,
gasLimit: 1_000,
});

await tx.waitForResult();
Expand All @@ -94,7 +90,7 @@ describe(__filename, () => {
const { error } = await safeExec(() =>
predicate.transfer(receiverWallet.address, predicateBalance, BaseAssetId, {
gasPrice,
gasLimit: 10_000,
gasLimit: 1_000,
})
);

Expand All @@ -106,17 +102,16 @@ describe(__filename, () => {
});

it('should fail when set wrong input data for predicate', async () => {
const provider = await Provider.create(FUEL_NETWORK_URL);
const predicateOwner = WalletUnlocked.generate({
provider,
});
const predicate = new Predicate(bin, predicateOwner.provider, abi);

const amountToPredicate = 200_000;
const amountToPredicate = 10_000;

const tx = await walletWithFunds.transfer(predicate.address, amountToPredicate, BaseAssetId, {
gasPrice,
gasLimit: 10_000,
gasLimit: 1_000,
});

await tx.waitForResult();
Expand All @@ -130,7 +125,7 @@ describe(__filename, () => {
const { error } = await safeExec(() =>
predicate.transfer(receiverWallet.address, amountToPredicate, BaseAssetId, {
gasPrice,
gasLimit: 10_000,
gasLimit: 1_000,
})
);

Expand All @@ -140,4 +135,48 @@ describe(__filename, () => {

expect((<Error>error).message).toMatch(errorMsg);
});

it('should ensure predicate createTransfer works as expected', async () => {
const predicate = new Predicate(bin, provider, abi);

const amountToPredicate = 10_000;

const tx = await walletWithFunds.transfer(predicate.address, amountToPredicate, BaseAssetId, {
gasPrice,
gasLimit: 1_000,
});

await tx.waitForResult();

const inputAddress = '0xfc05c23a8f7f66222377170ddcbfea9c543dff0dd2d2ba4d0478a4521423a9d4';

predicate.setData(inputAddress);

const receiverWallet = WalletUnlocked.generate({
provider,
});

// #region send-and-spend-funds-from-predicates-8
const transactionRequest = await predicate.createTransfer(
receiverWallet.address,
amountToPredicate,
BaseAssetId,
{
gasPrice,
gasLimit: 1_000,
}
);

const chainId = provider.getChainId();

const txId = transactionRequest.getTransactionId(chainId);

const res = await predicate.sendTransaction(transactionRequest);

await res.waitForResult();
// #endregion send-and-spend-funds-from-predicates-8
const txIdFromExecutedTx = res.id;

expect(txId).toEqual(txIdFromExecutedTx);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ Note the method transfer has two parameters: the recipient's address and the int

Once the predicate resolves with a return value `true` based on its predefined condition, our predicate successfully spends its funds by means of a transfer to a desired wallet.

---

In a similar approach, you can use the `createTransfer` method, which returns a `ScriptTransactionRequest`. Then, we can submit this transaction request by calling the `sendTransaction` method.

This can be useful if you need the transaction ID before actually submitting it to the node.
Torres-ssf marked this conversation as resolved.
Show resolved Hide resolved

<<< @/../../docs-snippets/src/guide/predicates/send-and-spend-funds-from-predicates.test.ts#send-and-spend-funds-from-predicates-8{ts:line-numbers}

## Spending Entire Predicate Held Amount

Trying to forward the entire amount held by the predicate results in an error because no funds are left to cover the transaction fees. Attempting this will result in an error message like:
Expand Down
3 changes: 1 addition & 2 deletions internal/check-imports/src/references.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Address } from '@fuel-ts/address';
import { BaseAssetId } from '@fuel-ts/address/configs';
import { ContractFactory } from '@fuel-ts/contract';
import { encrypt, decrypt } from '@fuel-ts/crypto';
import { hashTransaction, hashMessage } from '@fuel-ts/hasher';
import { hashMessage } from '@fuel-ts/hasher';
import { HDWallet } from '@fuel-ts/hdwallet';
import { AbstractPredicate } from '@fuel-ts/interfaces';
import { BN } from '@fuel-ts/math';
Expand Down Expand Up @@ -84,7 +84,6 @@ log(createConfig);
/**
* hasher
*/
log(hashTransaction);
log(hashMessage);

/**
Expand Down
2 changes: 0 additions & 2 deletions packages/hasher/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@
"@fuel-ts/address": "workspace:*",
"@fuel-ts/crypto": "workspace:*",
"@fuel-ts/math": "workspace:*",
"@fuel-ts/providers": "workspace:*",
"@fuel-ts/transactions": "workspace:*",
"@fuel-ts/utils": "workspace:*",
"ethers": "^6.7.1",
"ramda": "^0.29.0"
Expand Down
41 changes: 1 addition & 40 deletions packages/hasher/src/hasher.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { bn } from '@fuel-ts/math';
import { transactionRequestify } from '@fuel-ts/providers';
import signMessageTest from '@fuel-ts/testcases/src/signMessage.json';
import signTransactionTest from '@fuel-ts/testcases/src/signTransaction.json';

import { hashMessage, hash, hashTransaction } from './hasher';
import { hashMessage, hash } from './hasher';

describe('Hasher', () => {
it('Hash message', () => {
Expand All @@ -15,40 +12,4 @@ describe('Hasher', () => {
'0xf5ca38f748a1d6eaf726b8a42fb575c3c71f1864a8143301782de13da2d9202b'
);
});

it('Hash script transaction request', () => {
const transactionRequest = signTransactionTest.transaction;

expect(hashTransaction(transactionRequest, 0)).toEqual(signTransactionTest.hashedTransaction);
});

it('Hash script transaction with predicateGas', () => {
const transactionRequest = transactionRequestify({
type: 0,
gasPrice: '0x1',
gasLimit: '0x1dcd6500',
inputs: [
{
type: 2,
amount: '0x0',
sender: '0x00000000000000000000000059f2f1fcfe2474fd5f0b9ba1e73ca90b143eb8d0',
recipient: '0x809f80a984a60d641d4a6d284e3969ff380eb478e587bcba0ed1a3f0ef271ede',
witnessIndex: 0,
data: '0x3b42028d86539b607afeaf8d32501fa03c494ecad7e65a16a7a8ebc264f4b67a000000000000000000000000dadd1125b8df98a66abd5eb302c0d9ca5a061dc200000000000000000000000090f79bf6eb2c4f870365e785982e1f101e93b906456bdaffaf74fe03521754ac445d148033c0c6acf7d593132c43f92fdbc7324c0000000000000000000000000000000000000000000000008ac7230489e80000',
nonce: '0x0000000000000000000000000000000000000000000000000000000000000002',
predicate:
'0x1a405000910000206144000b6148000540411480504cc04c72580020295134165b501012615c000772680002595d7001616171015b61a0106165711a5b6400125b5c100b2404000024000000664e627bfc0db0bfa8f182efc913b552681143e328b555d9697c40ad0eb527ad',
predicateGasUsed: bn(25),
},
],
outputs: [],
witnesses: [],
script: '0x',
scriptData: '0x',
});

expect(hashTransaction(transactionRequest, 0)).toEqual(
'0xc0f5e25f37294c5b0218b377cae9622df03a05dc540374827c9e7a7f65560842'
);
});
});
93 changes: 1 addition & 92 deletions packages/hasher/src/hasher.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
import { ZeroBytes32 } from '@fuel-ts/address/configs';
import { bufferFromString } from '@fuel-ts/crypto';
import { bn } from '@fuel-ts/math';
import type { TransactionRequestLike } from '@fuel-ts/providers';
import { transactionRequestify } from '@fuel-ts/providers';
import { OutputType, InputType, TransactionCoder, TransactionType } from '@fuel-ts/transactions';
import type { BytesLike } from 'ethers';
import { sha256, concat } from 'ethers';
import { clone } from 'ramda';
import { sha256 } from 'ethers';

/**
* hash string messages with sha256
Expand All @@ -29,91 +23,6 @@ export function uint64ToBytesBE(value: number): Uint8Array {
return new Uint8Array(dataView.buffer);
}

/**
* Hash transaction request with sha256. [Read more](https://github.com/FuelLabs/fuel-specs/blob/master/specs/protocol/identifiers.md#transaction-id)
*
* @param transactionRequest - Transaction request to be hashed
* @returns sha256 hash of the transaction
*/
export function hashTransaction(transactionRequestLike: TransactionRequestLike, chainId: number) {
const transactionRequest = transactionRequestify(transactionRequestLike);
// Return a new transaction object without references to the original transaction request
const transaction = transactionRequest.toTransaction();

if (transaction.type === TransactionType.Script) {
transaction.receiptsRoot = ZeroBytes32;
}

// Zero out input fields
transaction.inputs = transaction.inputs.map((input) => {
const inputClone = clone(input);

switch (inputClone.type) {
// Zero out on signing: txPointer, predicateGasUsed
case InputType.Coin: {
inputClone.txPointer = {
blockHeight: 0,
txIndex: 0,
};
inputClone.predicateGasUsed = bn(0);
return inputClone;
}
// Zero out on signing: predicateGasUsed
case InputType.Message: {
inputClone.predicateGasUsed = bn(0);
return inputClone;
}
// Zero out on signing: txID, outputIndex, balanceRoot, stateRoot, and txPointer
case InputType.Contract: {
inputClone.txPointer = {
blockHeight: 0,
txIndex: 0,
};
inputClone.txID = ZeroBytes32;
inputClone.outputIndex = 0;
inputClone.balanceRoot = ZeroBytes32;
inputClone.stateRoot = ZeroBytes32;
return inputClone;
}
default:
return inputClone;
}
});
// Zero out output fields
transaction.outputs = transaction.outputs.map((output) => {
const outputClone = clone(output);

switch (outputClone.type) {
// Zero out on signing: balanceRoot, stateRoot
case OutputType.Contract: {
outputClone.balanceRoot = ZeroBytes32;
outputClone.stateRoot = ZeroBytes32;
return outputClone;
}
// Zero out on signing: amount
case OutputType.Change: {
outputClone.amount = bn(0);
return outputClone;
}
// Zero out on signing: amount, to and assetId
case OutputType.Variable: {
outputClone.to = ZeroBytes32;
outputClone.amount = bn(0);
outputClone.assetId = ZeroBytes32;
return outputClone;
}
default:
return outputClone;
}
});
transaction.witnessesCount = 0;
transaction.witnesses = [];

const chainIdBytes = uint64ToBytesBE(chainId);
const concatenatedData = concat([chainIdBytes, new TransactionCoder().encode(transaction)]);
return sha256(concatenatedData);
}

/**
* wrap sha256
*
Expand Down
Loading
Loading