-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathTransactionDataBlock.ts
More file actions
242 lines (212 loc) · 6.63 KB
/
TransactionDataBlock.ts
File metadata and controls
242 lines (212 loc) · 6.63 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
import { toB58 } from '@mysten/bcs';
import {
array,
assert,
define,
Infer,
integer,
is,
literal,
nullable,
object,
optional,
string,
union,
} from 'superstruct';
import { hashTypedData } from '../cryptography/hash';
import { normalizeSuiAddress, SuiObjectRef } from '../types';
import { builder } from './bcs';
import { TransactionType, TransactionBlockInput } from './Transactions';
import { BuilderCallArg, PureCallArg } from './Inputs';
import { create } from './utils';
export const TransactionExpiration = optional(
nullable(
union([
object({ Epoch: integer() }),
object({ None: union([literal(true), literal(null)]) }),
object({ ValidDuring: object({ minEpoch: integer(), maxEpoch: integer(), chain: string(), nonce: integer() }) }),
])
)
);
export type TransactionExpiration = Infer<typeof TransactionExpiration>;
const SuiAddress = string();
const StringEncodedBigint = define<string>('StringEncodedBigint', (val) => {
if (!['string', 'number', 'bigint'].includes(typeof val)) return false;
try {
BigInt(val as string);
return true;
} catch {
return false;
}
});
const GasConfig = object({
budget: optional(StringEncodedBigint),
price: optional(StringEncodedBigint),
payment: optional(array(SuiObjectRef)),
owner: optional(SuiAddress),
});
type GasConfig = Infer<typeof GasConfig>;
export const SerializedTransactionDataBuilder = object({
version: literal(1),
sender: optional(SuiAddress),
expiration: TransactionExpiration,
gasConfig: GasConfig,
inputs: array(TransactionBlockInput),
transactions: array(TransactionType),
});
export type SerializedTransactionDataBuilder = Infer<typeof SerializedTransactionDataBuilder>;
function prepareSuiAddress(address: string) {
return normalizeSuiAddress(address).replace('0x', '');
}
// NOTE: This value should be kept in sync with the corresponding value in
// crates/sui-protocol-config/src/lib.rs
export const TRANSACTION_DATA_MAX_SIZE = 128 * 1024;
export class TransactionBlockDataBuilder {
static fromKindBytes(bytes: Uint8Array) {
const kind = builder.de('TransactionKind', bytes);
const programmableTx = kind?.ProgrammableTransaction;
if (!programmableTx) {
throw new Error('Unable to deserialize from bytes.');
}
const serialized = create(
{
version: 1,
gasConfig: {},
inputs: programmableTx.inputs.map((value: unknown, index: number) =>
create(
{
kind: 'Input',
value,
index,
type: is(value, PureCallArg) ? 'pure' : 'object',
},
TransactionBlockInput
)
),
transactions: programmableTx.transactions,
},
SerializedTransactionDataBuilder
);
return TransactionBlockDataBuilder.restore(serialized);
}
static fromBytes(bytes: Uint8Array) {
const rawData = builder.de('TransactionData', bytes);
const data = rawData?.V1;
const programmableTx = data?.kind?.ProgrammableTransaction;
if (!data || !programmableTx) {
throw new Error('Unable to deserialize from bytes.');
}
const serialized = create(
{
version: 1,
sender: data.sender,
expiration: data.expiration,
gasConfig: data.gasData,
inputs: programmableTx.inputs.map((value: unknown, index: number) =>
create(
{
kind: 'Input',
value,
index,
type: is(value, PureCallArg) ? 'pure' : 'object',
},
TransactionBlockInput
)
),
transactions: programmableTx.transactions,
},
SerializedTransactionDataBuilder
);
return TransactionBlockDataBuilder.restore(serialized);
}
static restore(data: SerializedTransactionDataBuilder) {
assert(data, SerializedTransactionDataBuilder);
const transactionData = new TransactionBlockDataBuilder();
Object.assign(transactionData, data);
return transactionData;
}
/**
* Generate transaction digest.
*
* @param bytes BCS serialized transaction data
* @returns transaction digest.
*/
static getDigestFromBytes(bytes: Uint8Array) {
const hash = hashTypedData('TransactionData', bytes);
return toB58(hash);
}
version = 1 as const;
sender?: string;
expiration?: TransactionExpiration;
gasConfig: GasConfig;
inputs: TransactionBlockInput[];
transactions: TransactionType[];
constructor(clone?: TransactionBlockDataBuilder) {
this.sender = clone?.sender;
this.expiration = clone?.expiration;
this.gasConfig = clone?.gasConfig ?? {};
this.inputs = clone?.inputs ?? [];
this.transactions = clone?.transactions ?? [];
}
build({
overrides,
onlyTransactionKind,
}: {
overrides?: Pick<Partial<TransactionBlockDataBuilder>, 'sender' | 'gasConfig' | 'expiration'>;
onlyTransactionKind?: boolean;
} = {}) {
// Resolve inputs down to values:
const inputs = this.inputs.map((input) => {
assert(input.value, BuilderCallArg);
return input.value;
});
const kind = {
ProgrammableTransaction: {
inputs,
transactions: this.transactions,
},
};
if (onlyTransactionKind) {
return builder.ser('TransactionKind', kind, { maxSize: TRANSACTION_DATA_MAX_SIZE }).toBytes();
}
const expiration = overrides?.expiration ?? this.expiration;
const sender = overrides?.sender ?? this.sender;
const gasConfig = { ...this.gasConfig, ...overrides?.gasConfig };
if (!sender) {
throw new Error('Missing transaction sender');
}
if (!gasConfig.budget) {
throw new Error('Missing gas budget');
}
if (!gasConfig.payment) {
throw new Error('Missing gas payment');
}
if (!gasConfig.price) {
throw new Error('Missing gas price');
}
const transactionData = {
sender: prepareSuiAddress(sender),
expiration: expiration ? expiration : { None: true },
gasData: {
payment: gasConfig.payment,
owner: prepareSuiAddress(this.gasConfig.owner ?? sender),
price: BigInt(gasConfig.price),
budget: BigInt(gasConfig.budget),
},
kind: {
ProgrammableTransaction: {
inputs,
transactions: this.transactions,
},
},
};
return builder.ser('TransactionData', { V1: transactionData }, { maxSize: TRANSACTION_DATA_MAX_SIZE }).toBytes();
}
getDigest() {
const bytes = this.build({ onlyTransactionKind: false });
return TransactionBlockDataBuilder.getDigestFromBytes(bytes);
}
snapshot(): SerializedTransactionDataBuilder {
return create(this, SerializedTransactionDataBuilder);
}
}