-
Notifications
You must be signed in to change notification settings - Fork 54
/
cmlToCore.ts
392 lines (364 loc) · 15.8 KB
/
cmlToCore.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
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import * as Cardano from '../../Cardano';
import { CML } from '../CML';
import { SerializationError, SerializationFailure } from '../../errors';
import { bytesToHex } from '../../util/misc/bytesToHex';
import { createAssetId } from '../../Asset/util/assetId';
import { createCertificate } from './certificate';
import { usingAutoFree } from '@cardano-sdk/util';
export const txRequiredExtraSignatures = (
signatures: CML.Ed25519KeyHashes | undefined
): Cardano.Ed25519KeyHash[] | undefined =>
usingAutoFree((scope) => {
if (!signatures) return;
const requiredSignatures: Cardano.Ed25519KeyHash[] = [];
for (let i = 0; i < signatures.len(); i++) {
const signature = scope.manage(signatures.get(i));
const cardanoSignature = Cardano.Ed25519KeyHash(Buffer.from(signature.to_bytes()).toString('hex'));
requiredSignatures.push(cardanoSignature);
}
return requiredSignatures;
});
export const txWithdrawals = (withdrawals?: CML.Withdrawals): Cardano.Withdrawal[] | undefined =>
usingAutoFree((scope) => {
if (!withdrawals) return;
const result: Cardano.Withdrawal[] = [];
const keys = scope.manage(withdrawals.keys());
for (let i = 0; i < keys.len(); i++) {
const key = scope.manage(keys.get(i));
const value = scope.manage(withdrawals.get(key)!);
const rewardAccount = Cardano.RewardAccount(scope.manage(key.to_address()).to_bech32());
result.push({ quantity: BigInt(value!.to_str()), stakeAddress: rewardAccount });
}
return result;
});
export const value = (cslValue: CML.Value): Cardano.Value =>
usingAutoFree((scope) => {
const result: Cardano.Value = {
coins: BigInt(scope.manage(cslValue.coin()).to_str())
};
const multiasset = scope.manage(cslValue.multiasset());
if (!multiasset) {
return result;
}
result.assets = new Map();
const scriptHashes = scope.manage(multiasset.keys());
for (let scriptHashIdx = 0; scriptHashIdx < scriptHashes.len(); scriptHashIdx++) {
const scriptHash = scope.manage(scriptHashes.get(scriptHashIdx));
const assets = scope.manage(multiasset.get(scriptHash)!);
const assetKeys = scope.manage(assets.keys());
for (let assetIdx = 0; assetIdx < assetKeys.len(); assetIdx++) {
const assetName = scope.manage(assetKeys.get(assetIdx));
const assetAmount = BigInt(scope.manage(assets.get(assetName)!).to_str());
if (assetAmount > 0n) {
result.assets.set(createAssetId(scriptHash, assetName), assetAmount);
}
}
}
return result;
});
export const txIn = (input: CML.TransactionInput): Cardano.TxIn =>
usingAutoFree((scope) => ({
index: Number(scope.manage(input.index()).to_str()),
txId: Cardano.TransactionId.fromHexBlob(bytesToHex(scope.manage(input.transaction_id()).to_bytes()))
}));
export const txOut = (output: CML.TransactionOutput): Cardano.TxOut =>
usingAutoFree((scope) => {
const dataHashBytes = scope.manage(scope.manage(output.datum())?.as_data_hash())?.to_bytes();
return {
address: Cardano.Address(scope.manage(output.address()).to_bech32()),
datum: dataHashBytes ? Cardano.util.Hash32ByteBase16.fromHexBlob(bytesToHex(dataHashBytes)) : undefined,
value: value(scope.manage(output.amount()))
};
});
export const txOutputs = (outputs: CML.TransactionOutputs): Cardano.TxOut[] =>
usingAutoFree((scope) => {
const result: Cardano.TxOut[] = [];
for (let i = 0; i < outputs.len(); i++) {
result.push(txOut(scope.manage(outputs.get(i))));
}
return result;
});
export const txInputs = (inputs: CML.TransactionInputs): Cardano.TxIn[] =>
usingAutoFree((scope) => {
const result: Cardano.TxIn[] = [];
for (let i = 0; i < inputs.len(); i++) {
result.push(txIn(scope.manage(inputs.get(i))));
}
return result;
});
export const txCertificates = (certificates?: CML.Certificates): Cardano.Certificate[] | undefined =>
usingAutoFree((scope) => {
if (!certificates) return;
const result: Cardano.Certificate[] = [];
for (let i = 0; i < certificates.len(); i++) {
const cslCertificate = scope.manage(certificates.get(i));
result.push(createCertificate(cslCertificate));
}
return result;
});
export const txMint = (assets?: CML.Mint): Cardano.TokenMap | undefined =>
usingAutoFree((scope) => {
if (!assets) return;
const assetMap: Cardano.TokenMap = new Map();
const keys = scope.manage(assets.keys());
for (let i = 0; i < keys.len(); i++) {
const scriptHash = scope.manage(keys.get(i));
const mintAssets = scope.manage(assets.get(scriptHash));
if (!mintAssets) continue;
const mintKeys = scope.manage(mintAssets.keys());
for (let k = 0; k < mintKeys.len(); k++) {
const assetName = scope.manage(mintKeys.get(k));
const assetValueInt = scope.manage(mintAssets.get(assetName)!);
const assetId = createAssetId(scriptHash, assetName);
if (!assetValueInt) continue;
const quantity = assetValueInt.is_positive()
? BigInt(scope.manage(assetValueInt.as_positive())!.to_str())
: BigInt(scope.manage(assetValueInt.as_negative())!.to_str()) * -1n;
assetMap.set(assetId, quantity);
}
}
return assetMap;
});
export const txBody = (body: CML.TransactionBody): Cardano.TxBody =>
usingAutoFree((scope) => {
const cslScriptDataHash = scope.manage(body.script_data_hash());
const cslCollaterals = scope.manage(body.collateral());
return {
certificates: txCertificates(scope.manage(body.certs())),
collaterals: cslCollaterals && txInputs(cslCollaterals),
fee: BigInt(scope.manage(body.fee()).to_str()),
inputs: txInputs(scope.manage(body.inputs())),
mint: txMint(scope.manage(body.multiassets())),
outputs: txOutputs(scope.manage(body.outputs())),
requiredExtraSignatures: txRequiredExtraSignatures(scope.manage(body.required_signers())),
scriptIntegrityHash:
cslScriptDataHash && Cardano.util.Hash32ByteBase16(Buffer.from(cslScriptDataHash.to_bytes()).toString('hex')),
validityInterval: {
invalidBefore: Cardano.Slot(Number(scope.manage(body.validity_start_interval())?.to_str())),
invalidHereafter: Cardano.Slot(Number(scope.manage(body.ttl())?.to_str()))
},
withdrawals: txWithdrawals(scope.manage(body.withdrawals()))
};
});
export const txWitnessBootstrap = (bootstraps?: CML.BootstrapWitnesses): Cardano.BootstrapWitness[] | undefined =>
usingAutoFree((scope) => {
if (!bootstraps) return;
const result: Cardano.BootstrapWitness[] = [];
for (let i = 0; i < bootstraps.len(); i++) {
const bootstrap = scope.manage(bootstraps.get(i));
const attributes = scope.manage(bootstrap.attributes()).to_bytes();
const chainCode = bootstrap.chain_code();
result.push({
addressAttributes: attributes?.length > 0 ? Cardano.util.Base64Blob.fromBytes(attributes) : undefined,
chainCode: chainCode?.length > 0 ? Cardano.util.HexBlob.fromBytes(chainCode) : undefined,
key: Cardano.Ed25519PublicKey(
Buffer.from(scope.manage(scope.manage(bootstrap.vkey()).public_key()).as_bytes()).toString('hex')
),
signature: Cardano.Ed25519Signature(scope.manage(bootstrap.signature()).to_hex())
});
}
return result;
});
export const txWitnessRedeemers = (redeemers?: CML.Redeemers): Cardano.Redeemer[] | undefined =>
usingAutoFree((scope) => {
if (!redeemers) return;
const result: Cardano.Redeemer[] = [];
for (let j = 0; j < redeemers.len(); j++) {
const reedeemer = scope.manage(redeemers.get(j));
const index = scope.manage(reedeemer.index());
const data = scope.manage(reedeemer.data());
const exUnits = scope.manage(reedeemer.ex_units());
/**
* CML.RedeemerTagKind = Spend, Mint, Cert, Reward
* should we modify Cardano.Redeemer.purpose to match or just map reward to withdrawal ??
*/
const redeemerTagKind = scope.manage(reedeemer.tag()).kind();
result.push({
executionUnits: { memory: Number(scope.manage(exUnits.mem())), steps: Number(scope.manage(exUnits.steps())) },
index: Number(index),
purpose: Object.values(Cardano.RedeemerPurpose)[redeemerTagKind],
scriptHash: Cardano.util.Hash28ByteBase16(Buffer.from(data.to_bytes()).toString())
});
}
return result;
});
export const txWitnessSet = (witnessSet: CML.TransactionWitnessSet): Cardano.Witness =>
usingAutoFree((scope) => {
const vkeys: CML.Vkeywitnesses | undefined = scope.manage(witnessSet.vkeys())!;
const redeemers: CML.Redeemers | undefined = scope.manage(witnessSet.redeemers());
const bootstraps: CML.BootstrapWitnesses | undefined = scope.manage(witnessSet.bootstraps());
const txSignatures: Cardano.Signatures = new Map();
if (vkeys) {
for (let i = 0; i < vkeys!.len(); i++) {
const witness = scope.manage(vkeys.get(i));
txSignatures.set(
Cardano.Ed25519PublicKey(
Buffer.from(scope.manage(scope.manage(witness.vkey()).public_key()).as_bytes()).toString('hex')
),
Cardano.Ed25519Signature(scope.manage(witness.signature()).to_hex())
);
}
}
return {
// TODO: add support for scripts
bootstrap: txWitnessBootstrap(bootstraps),
// TODO: implement datums
redeemers: txWitnessRedeemers(redeemers),
signatures: txSignatures
};
});
export const txMetadatum = (transactionMetadatum: CML.TransactionMetadatum): Cardano.Metadatum =>
usingAutoFree((scope) => {
switch (transactionMetadatum.kind()) {
case CML.TransactionMetadatumKind.Bytes:
return transactionMetadatum.as_bytes();
case CML.TransactionMetadatumKind.Int: {
const int = scope.manage(transactionMetadatum.as_int())!;
if (int.is_positive()) return BigInt(scope.manage(int.as_positive())!.to_str());
return BigInt(scope.manage(int.as_negative())!.to_str()) * -1n;
}
case CML.TransactionMetadatumKind.MetadataList: {
const list = scope.manage(transactionMetadatum.as_list());
const metaDatumList: Cardano.Metadatum[] = [];
for (let j = 0; j < list.len(); j++) {
const listItem = scope.manage(list.get(j));
metaDatumList.push(txMetadatum(listItem));
}
return metaDatumList;
}
case CML.TransactionMetadatumKind.MetadataMap: {
const txMap = scope.manage(transactionMetadatum.as_map());
const metdatumMap = new Map<Cardano.Metadatum, Cardano.Metadatum>();
for (let i = 0; i < scope.manage(txMap.keys()).len(); i++) {
const mapKey = scope.manage(scope.manage(txMap.keys()).get(i));
const mapValue = scope.manage(txMap.get(mapKey));
metdatumMap.set(txMetadatum(mapKey), txMetadatum(mapValue));
}
return metdatumMap;
}
case CML.TransactionMetadatumKind.Text:
return transactionMetadatum.as_text();
default:
throw new SerializationError(SerializationFailure.InvalidType);
}
});
export const txMetadata = (auxiliaryMetadata?: CML.GeneralTransactionMetadata): Cardano.TxMetadata | undefined =>
usingAutoFree((scope) => {
if (!auxiliaryMetadata) return;
const auxiliaryMetadataMap: Cardano.TxMetadata = new Map();
const metadataKeys = auxiliaryMetadata.keys();
for (let i = 0; i < metadataKeys.len(); i++) {
const key = scope.manage(metadataKeys.get(i));
const transactionMetadatum = scope.manage(auxiliaryMetadata.get(key));
if (transactionMetadatum) {
scope.manage(transactionMetadatum);
auxiliaryMetadataMap.set(BigInt(key.to_str()), txMetadatum(transactionMetadatum));
}
}
return auxiliaryMetadataMap;
});
export const txAuxiliaryData = (auxiliaryData?: CML.AuxiliaryData): Cardano.AuxiliaryData | undefined =>
usingAutoFree((scope) => {
if (!auxiliaryData) return;
// TODO: create hash
const auxiliaryMetadata = scope.manage(auxiliaryData.metadata());
return {
body: {
blob: txMetadata(auxiliaryMetadata)
}
};
});
export const utxo = (cslUtxos: CML.TransactionUnspentOutput[]) =>
usingAutoFree((scope) =>
cslUtxos.map((cslUtxo) => [txIn(scope.manage(cslUtxo.input())), txOut(scope.manage(cslUtxo.output()))])
);
export const newTx = (cslTx: CML.Transaction): Cardano.Tx =>
usingAutoFree((scope) => {
const transactionHash = Cardano.TransactionId.fromHexBlob(
bytesToHex(scope.manage(CML.hash_transaction(scope.manage(cslTx.body()))).to_bytes())
);
const auxiliary_data = scope.manage(cslTx.auxiliary_data());
const witnessSet = scope.manage(cslTx.witness_set());
return {
auxiliaryData: txAuxiliaryData(auxiliary_data),
body: txBody(scope.manage(cslTx.body())),
id: transactionHash,
witness: txWitnessSet(witnessSet)
};
});
export const nativeScript = (script: CML.NativeScript): Cardano.NativeScript =>
usingAutoFree((scope) => {
let coreScript: Cardano.NativeScript;
const scriptKind = script.kind();
switch (scriptKind) {
case Cardano.NativeScriptKind.RequireSignature: {
coreScript = {
__type: Cardano.ScriptType.Native,
keyHash: Cardano.Ed25519KeyHash(
bytesToHex(scope.manage(scope.manage(script.as_script_pubkey())!.addr_keyhash()).to_bytes()).toString()
),
kind: Cardano.NativeScriptKind.RequireSignature
};
break;
}
case Cardano.NativeScriptKind.RequireAllOf: {
coreScript = {
__type: Cardano.ScriptType.Native,
kind: Cardano.NativeScriptKind.RequireAllOf,
scripts: new Array<Cardano.NativeScript>()
};
const scriptAll = scope.manage(script.as_script_all());
for (let i = 0; i < scope.manage(scriptAll!.native_scripts()).len(); ++i) {
coreScript.scripts.push(nativeScript(scope.manage(scope.manage(scriptAll!.native_scripts()).get(i))));
}
break;
}
case Cardano.NativeScriptKind.RequireAnyOf: {
coreScript = {
__type: Cardano.ScriptType.Native,
kind: Cardano.NativeScriptKind.RequireAnyOf,
scripts: new Array<Cardano.NativeScript>()
};
const scriptAny = scope.manage(script.as_script_any());
for (let i = 0; i < scope.manage(scriptAny!.native_scripts()).len(); ++i) {
coreScript.scripts.push(nativeScript(scope.manage(scope.manage(scriptAny!.native_scripts()).get(i))));
}
break;
}
case Cardano.NativeScriptKind.RequireMOf: {
const scriptMofK = scope.manage(script.as_script_n_of_k());
coreScript = {
__type: Cardano.ScriptType.Native,
kind: Cardano.NativeScriptKind.RequireMOf,
required: scriptMofK!.n(),
scripts: new Array<Cardano.NativeScript>()
};
for (let i = 0; i < scope.manage(scriptMofK!.native_scripts()).len(); ++i) {
coreScript.scripts.push(nativeScript(scope.manage(scope.manage(scriptMofK!.native_scripts()).get(i))));
}
break;
}
case Cardano.NativeScriptKind.RequireTimeBefore: {
coreScript = {
__type: Cardano.ScriptType.Native,
kind: Cardano.NativeScriptKind.RequireTimeBefore,
slot: Cardano.Slot(Number(scope.manage(scope.manage(script.as_timelock_expiry())!.slot()).to_str()))
};
break;
}
case Cardano.NativeScriptKind.RequireTimeAfter: {
coreScript = {
__type: Cardano.ScriptType.Native,
kind: Cardano.NativeScriptKind.RequireTimeAfter,
slot: Cardano.Slot(Number(scope.manage(scope.manage(script.as_timelock_start())!.slot()).to_str()))
};
break;
}
default:
throw new SerializationError(
SerializationFailure.InvalidNativeScriptKind,
`Native Script Kind value '${scriptKind}' is not supported.`
);
}
return coreScript;
});