-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
predicate.ts
172 lines (151 loc) · 4.96 KB
/
predicate.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import type { BytesLike } from '@ethersproject/bytes';
import { arrayify } from '@ethersproject/bytes';
import type { JsonAbiFragmentType, InputValue } from '@fuel-ts/abi-coder';
import { AbiCoder } from '@fuel-ts/abi-coder';
import { NativeAssetId } from '@fuel-ts/constants';
import { ContractUtils } from '@fuel-ts/contract';
import type { BigNumberish } from '@fuel-ts/math';
import type {
CoinQuantityLike,
TransactionRequestLike,
TransactionResult,
Coin,
} from '@fuel-ts/providers';
import { ScriptTransactionRequest } from '@fuel-ts/providers';
import { MAX_GAS_PER_TX } from '@fuel-ts/transactions';
import type { Wallet } from '@fuel-ts/wallet';
type BuildPredicateOptions = {
fundTransaction?: boolean;
} & Pick<TransactionRequestLike, 'gasLimit' | 'gasPrice' | 'bytePrice' | 'maturity'>;
export class Predicate {
bytes: Uint8Array;
address: BytesLike;
types?: ReadonlyArray<JsonAbiFragmentType>;
constructor(bytes: BytesLike, types?: ReadonlyArray<JsonAbiFragmentType>) {
this.bytes = arrayify(bytes);
this.address = ContractUtils.getContractRoot(this.bytes);
this.types = types;
}
async getPredicateBalance(wallet: Wallet, assetId: BytesLike = NativeAssetId): Promise<bigint> {
return wallet.provider.getBalance(this.address, assetId);
}
async buildPredicateTransaction(
wallet: Wallet,
amountToPredicate: BigNumberish,
assetId: BytesLike = NativeAssetId,
predicateOptions?: BuildPredicateOptions
): Promise<ScriptTransactionRequest> {
const options = {
fundTransaction: true,
...predicateOptions,
};
const request = new ScriptTransactionRequest({
gasLimit: MAX_GAS_PER_TX,
...options,
});
// output is locked behind predicate
request.addCoinOutput(this.address, amountToPredicate, assetId);
const requiredCoinQuantities: CoinQuantityLike[] = [];
if (options.fundTransaction) {
requiredCoinQuantities.push(request.calculateFee());
}
if (requiredCoinQuantities.length) {
const coins = await wallet.getCoinsToSpend(requiredCoinQuantities);
request.addCoins(coins);
}
return request;
}
async submitPredicate(
wallet: Wallet,
amountToPredicate: BigNumberish,
assetId: BytesLike = NativeAssetId,
options?: BuildPredicateOptions
): Promise<TransactionResult<'success'>> {
const request = await this.buildPredicateTransaction(
wallet,
amountToPredicate,
assetId,
options
);
const response = await wallet.sendTransaction(request);
return response.waitForResult();
}
async buildSpendPredicate(
wallet: Wallet,
amountToSpend: BigNumberish,
receiverAddress: BytesLike,
predicateData?: InputValue[],
assetId: BytesLike = NativeAssetId,
predicateOptions?: BuildPredicateOptions
): Promise<ScriptTransactionRequest> {
const predicateCoins: Coin[] = await wallet.provider.getCoinsToSpend(this.address, [
[amountToSpend, assetId],
]);
const options = {
fundTransaction: true,
...predicateOptions,
};
const request = new ScriptTransactionRequest({
gasLimit: MAX_GAS_PER_TX,
...options,
});
let encoded: undefined | Uint8Array;
if (predicateData && this.types) {
const abiCoder = new AbiCoder();
encoded = abiCoder.encode(this.types, predicateData);
}
let totalInPredicate = 0n;
predicateCoins.forEach((coin: Coin) => {
totalInPredicate += coin.amount;
request.addCoin({
...coin,
predicate: this.bytes,
predicateData: encoded,
} as Coin);
request.outputs = [];
});
// output sent to receiver
request.addCoinOutput(receiverAddress, totalInPredicate, assetId);
const requiredCoinQuantities: CoinQuantityLike[] = [];
if (options.fundTransaction) {
requiredCoinQuantities.push(request.calculateFee());
}
if (requiredCoinQuantities.length) {
const coins = await wallet.getCoinsToSpend(requiredCoinQuantities);
request.addCoins(coins);
}
return request;
}
async submitSpendPredicate(
wallet: Wallet,
amountToSpend: BigNumberish,
receiverAddress: BytesLike,
predicateData?: InputValue[],
assetId: BytesLike = NativeAssetId,
options?: BuildPredicateOptions
): Promise<TransactionResult<'success'>> {
const request = await this.buildSpendPredicate(
wallet,
amountToSpend,
receiverAddress,
predicateData,
assetId,
options
);
try {
const response = await wallet.sendTransaction(request);
return await response.waitForResult();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) {
const errors: { message: string }[] = error?.response?.errors || [];
if (
errors.some(({ message }) =>
message.includes('unexpected block execution error TransactionValidity(InvalidPredicate')
)
) {
throw new Error('Invalid Predicate');
}
throw error;
}
}
}