-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathTransactionBlock.ts
More file actions
309 lines (273 loc) · 10.5 KB
/
TransactionBlock.ts
File metadata and controls
309 lines (273 loc) · 10.5 KB
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import { fromB64 } from '@mysten/bcs';
import { is, mask } from 'superstruct';
import { ObjectId, SuiObjectRef } from '../types';
import { Transactions, TransactionArgument, TransactionType, TransactionBlockInput } from './Transactions';
import { BuilderCallArg, getIdFromCallArg, Inputs, ObjectCallArg } from './Inputs';
import { TransactionBlockDataBuilder, TransactionExpiration } from './TransactionDataBlock';
import { TypeTagSerializer } from '../txn-data-serializers/type-tag-serializer';
import { create } from './utils';
type TransactionResult = TransactionArgument & TransactionArgument[];
function createTransactionResult(index: number): TransactionResult {
const baseResult: TransactionArgument = { kind: 'Result', index };
const nestedResults: TransactionArgument[] = [];
const nestedResultFor = (resultIndex: number): TransactionArgument =>
(nestedResults[resultIndex] ??= {
kind: 'NestedResult',
index,
resultIndex,
});
return new Proxy(baseResult, {
set() {
throw new Error('The transaction result is a proxy, and does not support setting properties directly');
},
// TODO: Instead of making this return a concrete argument, we should ideally
// make it reference-based (so that this gets resolved at build-time), which
// allows re-ordering transactions.
get(target, property) {
// This allows this transaction argument to be used in the singular form:
if (property in target) {
return Reflect.get(target, property);
}
// Support destructuring:
if (property === Symbol.iterator) {
return function* () {
let i = 0;
while (true) {
yield nestedResultFor(i);
i++;
}
};
}
if (typeof property === 'symbol') return;
const resultIndex = parseInt(property, 10);
if (Number.isNaN(resultIndex) || resultIndex < 0) return;
return nestedResultFor(resultIndex);
},
}) as TransactionResult;
}
const TRANSACTION_BRAND = Symbol.for('@mysten/transaction');
// The maximum number of gas objects that can be selected for one transaction.
const MAX_GAS_OBJECTS = 256;
// The maximum gas that is allowed.
const MAX_GAS = 1000000000;
// A guess about how much overhead each coin provides for gas calculations.
// @ts-ignore
const GAS_OVERHEAD_PER_COIN = 10n;
interface BuildOptions {
onlyTransactionKind?: boolean;
}
/**
* Transaction Builder
*/
export class TransactionBlock {
/** Returns `true` if the object is an instance of the Transaction builder class. */
static is(obj: unknown): obj is TransactionBlock {
return !!obj && typeof obj === 'object' && (obj as any)[TRANSACTION_BRAND] === true;
}
/**
* Converts from a serialize transaction kind (built with `build({ onlyTransactionKind: true })`) to a `Transaction` class.
* Supports either a byte array, or base64-encoded bytes.
*/
static fromKind(serialized: string | Uint8Array) {
const tx = new TransactionBlock();
tx.#blockData = TransactionBlockDataBuilder.fromKindBytes(
typeof serialized === 'string' ? fromB64(serialized) : serialized
);
return tx;
}
/**
* Converts from a serialized transaction format to a `Transaction` class.
* There are two supported serialized formats:
* - A string returned from `Transaction#serialize`. The serialized format must be compatible, or it will throw an error.
* - A byte array (or base64-encoded bytes) containing BCS transaction data.
*/
static from(serialized: string | Uint8Array) {
const tx = new TransactionBlock();
// Check for bytes:
if (typeof serialized !== 'string' || !serialized.startsWith('{')) {
tx.#blockData = TransactionBlockDataBuilder.fromBytes(
typeof serialized === 'string' ? fromB64(serialized) : serialized
);
} else {
tx.#blockData = TransactionBlockDataBuilder.restore(JSON.parse(serialized));
}
return tx;
}
/** A helper to retrieve the Transaction builder `Transactions` */
static get Transactions() {
return Transactions;
}
/** A helper to retrieve the Transaction builder `Inputs` */
static get Inputs() {
return Inputs;
}
setSender(sender: string) {
this.#blockData.sender = sender;
}
/**
* Sets the sender only if it has not already been set.
* This is useful for sponsored transaction flows where the sender may not be the same as the signer address.
*/
setSenderIfNotSet(sender: string) {
if (!this.#blockData.sender) {
this.#blockData.sender = sender;
}
}
setExpiration(expiration?: TransactionExpiration) {
this.#blockData.expiration = expiration;
}
setGasPrice(price: number | bigint) {
this.#blockData.gasConfig.price = String(price);
}
setGasBudget(budget: number | bigint) {
this.#blockData.gasConfig.budget = String(budget);
}
setGasOwner(owner: string) {
this.#blockData.gasConfig.owner = owner;
}
setGasPayment(payments: SuiObjectRef[]) {
if (payments.length >= MAX_GAS_OBJECTS) {
throw new Error(`Payment objects exceed maximum amount ${MAX_GAS_OBJECTS}`);
}
this.#blockData.gasConfig.payment = payments.map((payment) => mask(payment, SuiObjectRef));
}
#blockData: TransactionBlockDataBuilder;
/** Get a snapshot of the transaction data, in JSON form: */
get blockData() {
return this.#blockData.snapshot();
}
// Used to brand transaction classes so that they can be identified, even between multiple copies
// of the builder.
get [TRANSACTION_BRAND]() {
return true;
}
constructor(transaction?: TransactionBlock) {
this.#blockData = new TransactionBlockDataBuilder(transaction ? transaction.#blockData : undefined);
}
/** Returns an argument for the gas coin, to be used in a transaction. */
get gas(): TransactionArgument {
return { kind: 'GasCoin' };
}
/**
* Dynamically create a new input, which is separate from the `input`. This is important
* for generated clients to be able to define unique inputs that are non-overlapping with the
* defined inputs.
*
* For `Uint8Array` type automatically convert the input into a `Pure` CallArg, since this
* is the format required for custom serialization.
*
*/
input(type: 'object' | 'pure', value?: unknown) {
const index = this.#blockData.inputs.length;
const input = create(
{
kind: 'Input',
// bigints can't be serialized to JSON, so just string-convert them here:
value: typeof value === 'bigint' ? String(value) : value,
index,
type,
},
TransactionBlockInput
);
this.#blockData.inputs.push(input);
return input;
}
/**
* Add a new object input to the transaction.
*/
object(value: ObjectId | ObjectCallArg) {
const id = getIdFromCallArg(value);
// deduplicate
const inserted = this.#blockData.inputs.find((i) => i.type === 'object' && id === getIdFromCallArg(i.value));
return inserted ?? this.input('object', value);
}
/**
* Add a new non-object input to the transaction.
*/
pure(
/**
* The pure value that will be used as the input value. If this is a Uint8Array, then the value
* is assumed to be raw bytes, and will be used directly.
*/
value: unknown,
/**
* The BCS type to serialize the value into. If not provided, the type will automatically be determined
* based on how the input is used.
*/
type?: string
) {
// TODO: we can also do some deduplication here
return this.input(
'pure',
value instanceof Uint8Array ? Inputs.Pure(value) : type ? Inputs.Pure(value, type) : value
);
}
/** Add a transaction to the transaction block. */
add(transaction: TransactionType) {
const index = this.#blockData.transactions.push(transaction);
return createTransactionResult(index - 1);
}
// Method shorthands:
/**
* Create a BalanceWithdrawal argument that withdraws `amount` from the sender's
* address balance at execution time. Pass this as an argument to
* `0x2::coin::redeem_funds` to receive a `Coin<T>` object:
*
* ```typescript
* const [coin] = tx.moveCall({
* target: '0x2::coin::redeem_funds',
* typeArguments: ['0x2::sui::SUI'],
* arguments: [tx.withdrawal({ amount: 1_000_000n })],
* });
* tx.transferObjects([coin], recipientAddress);
* ```
*
* @param amount - amount in base units (e.g. MIST for SUI)
* @param type - coin type string, defaults to `'0x2::sui::SUI'`
*/
withdrawal({ amount, type: coinType = '0x2::sui::SUI' }: { amount: bigint | number; type?: string }): TransactionArgument {
const typeTag = TypeTagSerializer.parseFromStr(coinType, true);
return this.input('object', Inputs.BalanceWithdrawal(amount, typeTag));
}
splitCoins(...args: Parameters<(typeof Transactions)['SplitCoins']>) {
return this.add(Transactions.SplitCoins(...args));
}
mergeCoins(...args: Parameters<(typeof Transactions)['MergeCoins']>) {
return this.add(Transactions.MergeCoins(...args));
}
publish(...args: Parameters<(typeof Transactions)['Publish']>) {
return this.add(Transactions.Publish(...args));
}
moveCall(...args: Parameters<(typeof Transactions)['MoveCall']>) {
return this.add(Transactions.MoveCall(...args));
}
transferObjects(...args: Parameters<(typeof Transactions)['TransferObjects']>) {
return this.add(Transactions.TransferObjects(...args));
}
makeMoveVec(...args: Parameters<(typeof Transactions)['MakeMoveVec']>) {
return this.add(Transactions.MakeMoveVec(...args));
}
/**
* Serialize the transaction to a string so that it can be sent to a separate context.
* This is different from `build` in that it does not serialize to BCS bytes, and instead
* uses a separate format that is unique to the transaction builder. This allows
* us to serialize partially-complete transactions, that can then be completed and
* built in a separate context.
*
* For example, a dapp can construct a transaction, but not provide gas objects
* or a gas budget. The transaction then can be sent to the wallet, where this
* information is automatically filled in (e.g. by querying for coin objects
* and performing a dry run).
*/
serialize() {
return JSON.stringify(this.#blockData.snapshot());
}
/** Build the transaction to BCS bytes. */
async build({ onlyTransactionKind }: BuildOptions = {}): Promise<Uint8Array> {
return this.#blockData.build({ onlyTransactionKind });
}
/** Derive transaction digest */
async getDigest(): Promise<string> {
return this.#blockData.getDigest();
}
}