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: use submitAndAwait graphql endpoint #1615

Merged
merged 35 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
da7f580
feat: use submitAndAwait endpoint
nedsalk Jan 5, 2024
2414b82
feat: don't fetch when transaction is already executed
nedsalk Jan 5, 2024
45ea207
test: fix assumptions
nedsalk Jan 5, 2024
d82b092
Merge branch 'rc/salamander' into ns/feat/submit-and-await
nedsalk Jan 5, 2024
a243d44
fix: better typedocs
nedsalk Jan 5, 2024
bd56166
test: added tests to cover all methods that have `awaitExecution` on …
nedsalk Jan 5, 2024
f40a9e6
Merge remote-tracking branch 'origin/rc/salamander' into ns/feat/subm…
nedsalk Jan 5, 2024
14caf98
Merge branch 'rc/salamander' into ns/feat/submit-and-await
nedsalk Jan 5, 2024
8e68217
feat: use `submitAndAwait` by default in `BaseInvocationScope`
nedsalk Jan 9, 2024
d3a0cff
Merge branch 'rc/salamander' into ns/feat/submit-and-await
nedsalk Jan 9, 2024
bb9e117
refactor: use `for-await-of` instead of `ReadableStream` piping
nedsalk Jan 9, 2024
01267c0
Revert "refactor: use `for-await-of` instead of `ReadableStream` piping"
nedsalk Jan 9, 2024
9b3a057
feat: close stream when iterator finishes
nedsalk Jan 10, 2024
9a70a14
feat: don't allow `awaitExecution` passing in `BaseInvocationScope`
nedsalk Jan 10, 2024
7ff5d16
fix: stream not ending when connection is closed by node
nedsalk Jan 11, 2024
f5c120d
fix: add missing keep-alive message handling
nedsalk Jan 11, 2024
96b60ab
fix: throw `FuelError` in subscription
nedsalk Jan 11, 2024
9b78417
chore: revert changes on accounts
nedsalk Jan 11, 2024
471480c
chore: changeset
nedsalk Jan 11, 2024
e1a9b6a
chore: additional reverts
nedsalk Jan 11, 2024
35493ab
revert changes
nedsalk Jan 11, 2024
8cf8d98
fix: `awaitExecution` on account's sendTransaction
nedsalk Jan 11, 2024
f3d3c7f
chore: update changeset
nedsalk Jan 11, 2024
6bbb031
fix: failing build
nedsalk Jan 11, 2024
20ed3a5
reapply awaitExecution in utils and contract-factory
nedsalk Jan 11, 2024
6bbb6a4
Merge branch 'rc/salamander' into ns/feat/submit-and-await
nedsalk Jan 12, 2024
0b6e3a9
Merge branch 'rc/salamander' into ns/feat/submit-and-await
nedsalk Jan 12, 2024
73c9f6a
Merge branch 'rc/salamander' into ns/feat/submit-and-await
nedsalk Jan 15, 2024
282cb67
Merge branch 'rc/salamander' into ns/feat/submit-and-await
nedsalk Jan 15, 2024
9177c4f
Merge branch 'rc/salamander' into ns/feat/submit-and-await
nedsalk Jan 15, 2024
ca6b643
revert: bugfix, moved to #1597
nedsalk Jan 16, 2024
818d263
Merge branch 'rc/salamander' into ns/feat/submit-and-await
nedsalk Jan 16, 2024
2698eba
Merge branch 'rc/salamander' into ns/feat/submit-and-await
nedsalk Jan 16, 2024
e26e52a
Merge branch 'rc/salamander' into ns/feat/submit-and-await
nedsalk Jan 17, 2024
1fa9329
Merge branch 'rc/salamander' into ns/feat/submit-and-await
nedsalk Jan 17, 2024
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
5 changes: 1 addition & 4 deletions apps/docs-snippets/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@ export const getTestWallet = async (seedQuantities?: CoinQuantityLike[]) => {
await genesisWallet.fund(request, requiredQuantities, minFee);

// execute the transaction, transferring resources to the test wallet
const response = await genesisWallet.sendTransaction(request);

// wait for the transaction to be confirmed
await response.wait();
await genesisWallet.sendTransaction(request, { awaitExecution: true });
danielbate marked this conversation as resolved.
Show resolved Hide resolved

// return the test wallet
return testWallet;
Expand Down
5 changes: 3 additions & 2 deletions packages/contract/src/contract-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,9 @@ export default class ContractFactory {
transactionRequest.maxFee = this.account.provider.getGasConfig().maxGasPerTx;

await this.account.fund(transactionRequest, requiredQuantities, maxFee);
const response = await this.account.sendTransaction(transactionRequest);
await response.wait();
await this.account.sendTransaction(transactionRequest, {
awaitExecution: true,
});

return new Contract(contractId, this.interface, this.account);
}
Expand Down
114 changes: 114 additions & 0 deletions packages/fuel-gauge/src/await-execution.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { launchNode } from '@fuel-ts/wallet/test-utils';
import {
Provider,
WalletUnlocked,
randomBytes,
Wallet,
BaseAssetId,
FUEL_NETWORK_URL,
} from 'fuels';

import { getSetupContract } from './utils';

/**
* @group node
*/
describe('await-execution', () => {
test('awaiting execution of a transaction on the provider works', async () => {
const { cleanup, ip, port } = await launchNode({
args: ['--poa-interval-period', '400ms'],
});
const nodeProvider = await Provider.create(`http://${ip}:${port}/graphql`);
danielbate marked this conversation as resolved.
Show resolved Hide resolved

const genesisWallet = new WalletUnlocked(
process.env.GENESIS_SECRET || randomBytes(32),
nodeProvider
);

const destination = Wallet.generate({ provider: nodeProvider });

const transfer = await genesisWallet.createTransfer(destination.address, 100, BaseAssetId, {
gasPrice: nodeProvider.getGasConfig().minGasPrice,
gasLimit: 10_000,
});

transfer.updateWitnessByOwner(
genesisWallet.address,
await genesisWallet.signTransaction(transfer)
);

const response = await nodeProvider.sendTransaction(transfer, { awaitExecution: true });

expect(response.gqlTransaction?.status?.type).toBe('SuccessStatus');

cleanup();
});
test('calling contracts with awaitExecution works', async () => {
const contract = await getSetupContract('coverage-contract')();
const sendTransactionSpy = vi.spyOn(contract.provider, 'sendTransaction');
const gasPrice = contract.provider.getGasConfig().minGasPrice;

const { value } = await contract.functions
.echo_u8(3)
.txParams({ gasPrice, gasLimit: 10_000 })
.call({ awaitExecution: true });
nedsalk marked this conversation as resolved.
Show resolved Hide resolved
expect(value).toBe(3);

expect(sendTransactionSpy).toHaveBeenCalledTimes(1);
const awaitExecutionArg = sendTransactionSpy.mock.calls[0][1];
expect(awaitExecutionArg).toMatchObject({ awaitExecution: true });
});

test('transferring funds with awaitExecution works', async () => {
const provider = await Provider.create(FUEL_NETWORK_URL);
const genesisWallet = new WalletUnlocked(
process.env.GENESIS_SECRET || randomBytes(32),
provider
);

const sendTransactionSpy = vi.spyOn(provider, 'sendTransaction');

const destination = Wallet.generate({ provider });

await genesisWallet.transfer(
destination.address,
100,
BaseAssetId,
{
gasPrice: provider.getGasConfig().minGasPrice,
gasLimit: 10_000,
},
{ awaitExecution: true }
);

expect(sendTransactionSpy).toHaveBeenCalledTimes(1);
const awaitExecutionArg = sendTransactionSpy.mock.calls[0][1];
expect(awaitExecutionArg).toMatchObject({ awaitExecution: true });
});

test('withdrawToBaseLayer works with awaitExecution', async () => {
const provider = await Provider.create(FUEL_NETWORK_URL);
const genesisWallet = new WalletUnlocked(
process.env.GENESIS_SECRET || randomBytes(32),
provider
);

const sendTransactionSpy = vi.spyOn(provider, 'sendTransaction');

const destination = Wallet.generate({ provider });

await genesisWallet.withdrawToBaseLayer(
destination.address,
100,
{
gasPrice: provider.getGasConfig().minGasPrice,
gasLimit: 10_000,
},
{ awaitExecution: true }
);

expect(sendTransactionSpy).toHaveBeenCalledTimes(1);
const awaitExecutionArg = sendTransactionSpy.mock.calls[0][1];
expect(awaitExecutionArg).toMatchObject({ awaitExecution: true });
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ export const fundPredicate = async <T extends InputValue[]>(
request.gasLimit = gasUsed;
await wallet.fund(request, requiredQuantities, minFee);

const tx = await wallet.sendTransaction(request);
await tx.waitForResult();
await wallet.sendTransaction(request, { awaitExecution: true });

return predicate.getBalance();
};
4 changes: 2 additions & 2 deletions packages/interfaces/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export abstract class AbstractAccount {
abstract address: AbstractAddress;
abstract provider: unknown;
abstract getResourcesToSpend(quantities: any[], options?: any): any;
abstract sendTransaction(transactionRequest: any): any;
abstract sendTransaction(transactionRequest: any, options?: any): any;
abstract simulateTransaction(transactionRequest: any): any;
abstract fund(transactionRequest: any, quantities: any, fee: any): Promise<void>;
}
Expand All @@ -74,7 +74,7 @@ export abstract class AbstractProgram {
};

abstract provider: {
sendTransaction(transactionRequest: any): any;
sendTransaction(transactionRequest: any, options?: any): any;
} | null;
}

Expand Down
8 changes: 6 additions & 2 deletions packages/predicate/src/predicate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type { BigNumberish } from '@fuel-ts/math';
import type {
CallResult,
Provider,
ProviderSendTxParams,
TransactionRequest,
TransactionRequestLike,
TransactionResponse,
Expand Down Expand Up @@ -113,9 +114,12 @@ export class Predicate<ARGS extends InputValue[]> extends Account implements Abs
* @param transactionRequestLike - The transaction request-like object.
* @returns A promise that resolves to the transaction response.
*/
sendTransaction(transactionRequestLike: TransactionRequestLike): Promise<TransactionResponse> {
sendTransaction(
transactionRequestLike: TransactionRequestLike,
options?: Pick<ProviderSendTxParams, 'awaitExecution'>
): Promise<TransactionResponse> {
const transactionRequest = this.populateTransactionPredicateData(transactionRequestLike);
return super.sendTransaction(transactionRequest);
return super.sendTransaction(transactionRequest, options);
}

/**
Expand Down
8 changes: 5 additions & 3 deletions packages/program/src/functions/base-invocation-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { ErrorCode, FuelError } from '@fuel-ts/errors';
import type { AbstractContract, AbstractProgram } from '@fuel-ts/interfaces';
import type { BN } from '@fuel-ts/math';
import { bn, toNumber } from '@fuel-ts/math';
import type { Provider, CoinQuantity } from '@fuel-ts/providers';
import type { Provider, CoinQuantity, ProviderSendTxParams } from '@fuel-ts/providers';
import { ScriptTransactionRequest } from '@fuel-ts/providers';
import { InputType } from '@fuel-ts/transactions';
import type { BaseWalletUnlocked } from '@fuel-ts/wallet';
Expand Down Expand Up @@ -288,7 +288,9 @@ export class BaseInvocationScope<TReturn = any> {
*
* @returns The result of the function invocation.
*/
async call<T = TReturn>(): Promise<FunctionInvocationResult<T>> {
async call<T = TReturn>(
options?: Pick<ProviderSendTxParams, 'awaitExecution'>
): Promise<FunctionInvocationResult<T>> {
assert(this.program.account, 'Wallet is required!');

const transactionRequest = await this.getTransactionRequest();
Expand All @@ -297,7 +299,7 @@ export class BaseInvocationScope<TReturn = any> {

await this.fundWithRequiredCoins(maxFee);

const response = await this.program.account.sendTransaction(transactionRequest);
const response = await this.program.account.sendTransaction(transactionRequest, options);

return FunctionInvocationResult.build<T>(
this.functionInvocationScopes,
Expand Down
33 changes: 28 additions & 5 deletions packages/providers/src/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,16 @@ export type ProviderCallParams = UTXOValidationParams & EstimateTransactionParam
/**
* Provider Send transaction params
*/
export type ProviderSendTxParams = EstimateTransactionParams;
export type ProviderSendTxParams = EstimateTransactionParams & {
/**
* By default, the promise will resolve immediately after the transaction is submitted.
*
* If set to true, the promise will resolve only when the transaction changes status
* from `SubmittedStatus` to one of `SuccessStatus`, `FailureStatus` or `SqueezedOutStatus`.
*
*/
awaitExecution?: boolean;
};

/**
* URL - Consensus Params mapping.
Expand Down Expand Up @@ -564,7 +573,7 @@ export default class Provider {
// #region Provider-sendTransaction
async sendTransaction(
transactionRequestLike: TransactionRequestLike,
{ estimateTxDependencies = true }: ProviderSendTxParams = {}
{ estimateTxDependencies = true, awaitExecution = false }: ProviderSendTxParams = {}
): Promise<TransactionResponse> {
const transactionRequest = transactionRequestify(transactionRequestLike);
this.#cacheInputs(transactionRequest.inputs);
Expand All @@ -573,7 +582,6 @@ export default class Provider {
}
// #endregion Provider-sendTransaction

const encodedTransaction = hexlify(transactionRequest.toTransactionBytes());
const { gasUsed, minGasPrice } = await this.getTransactionCost(transactionRequest, [], {
estimateTxDependencies: false,
estimatePredicates: false,
Expand All @@ -595,12 +603,27 @@ export default class Provider {
);
}

const encodedTransaction = hexlify(transactionRequest.toTransactionBytes());

if (awaitExecution) {
const subscription = this.operations.submitAndAwait({ encodedTransaction });
for await (const { submitAndAwait } of subscription) {
if (submitAndAwait.type === 'SuccessStatus') {
break;
}
}
nedsalk marked this conversation as resolved.
Show resolved Hide resolved

const transactionId = transactionRequest.getTransactionId(this.getChainId());
const response = new TransactionResponse(transactionId, this);
await response.fetch();
return response;
}

const {
submit: { id: transactionId },
} = await this.operations.submit({ encodedTransaction });

const response = new TransactionResponse(transactionId, this);
return response;
return new TransactionResponse(transactionId, this);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,14 +197,12 @@ export class TransactionResponse {
return transactionSummary;
}

/**
* Waits for transaction to complete and returns the result.
*
* @returns The completed transaction result
*/
async waitForResult<TTransactionType = void>(
contractsAbiMap?: AbiMap
): Promise<TransactionResult<TTransactionType>> {
private async waitForStatusChange() {
const status = this.gqlTransaction?.status?.type;
if (status && status !== 'SubmittedStatus') {
return;
}

const subscription = this.provider.operations.statusChange({
transactionId: this.id,
});
Expand All @@ -216,6 +214,17 @@ export class TransactionResponse {
}

await this.fetch();
}

/**
* Waits for transaction to complete and returns the result.
*
* @returns The completed transaction result
*/
async waitForResult<TTransactionType = void>(
contractsAbiMap?: AbiMap
): Promise<TransactionResult<TTransactionType>> {
await this.waitForStatusChange();

const transactionSummary = await this.getTransactionSummary<TTransactionType>(contractsAbiMap);

Expand Down
6 changes: 3 additions & 3 deletions packages/wallet/src/account.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ describe('Account', () => {
);

expect(sendTransactionSpy).toHaveBeenCalledTimes(1);
expect(sendTransactionSpy).toHaveBeenCalledWith(request);
expect(sendTransactionSpy).toHaveBeenCalledWith(request, undefined);
});

it('should execute withdrawToBaseLayer just fine', async () => {
Expand Down Expand Up @@ -392,7 +392,7 @@ describe('Account', () => {
expect(scriptTransactionRequest).toHaveBeenCalledTimes(1);

expect(sendTransaction).toHaveBeenCalledTimes(1);
expect(sendTransaction).toHaveBeenCalledWith(request);
expect(sendTransaction).toHaveBeenCalledWith(request, undefined);

expect(getTransactionCost).toHaveBeenCalledTimes(1);
expect(fund).toHaveBeenCalledTimes(1);
Expand All @@ -405,7 +405,7 @@ describe('Account', () => {
expect(scriptTransactionRequest).toHaveBeenCalledTimes(2);

expect(sendTransaction).toHaveBeenCalledTimes(2);
expect(sendTransaction).toHaveBeenCalledWith(request);
expect(sendTransaction).toHaveBeenCalledWith(request, undefined);
});

it('should execute sendTransaction just fine', async () => {
Expand Down
Loading
Loading