Skip to content

Commit

Permalink
fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
micahkendall committed Sep 4, 2024
1 parent 0dd7bef commit 4a2c0a0
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 44 deletions.
41 changes: 27 additions & 14 deletions examples/u5c/index.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,33 @@
// Step #1
// Import Blaze SDK and U5C provider
import { Bip32PrivateKey, mnemonicToEntropy, wordlist } from "../../packages/blaze-core/dist/index.js";
import { HotWallet, Core, Blaze, U5C } from "../../packages/blaze-sdk/dist/index.js";
import {
Bip32PrivateKey,
mnemonicToEntropy,
wordlist,
} from "../../packages/blaze-core/dist/index.js";
import {
HotWallet,
Core,
Blaze,
U5C,
} from "../../packages/blaze-sdk/dist/index.js";

// Step #2
// Create a new U5C provider
// In this example we use Demeter hosted UTXO provider
// but you can run a local Dolos https://github.com/txpipe/dolos instance and connect to its UTxO endpoint
// If this is the case then you can remove the headers field
const provider = new U5C({
url: "http://localhost:50051",
headers: {
"dmtr-api-key": "<api-key>"
}
url: "http://localhost:50051",
headers: {
"dmtr-api-key": "<api-key>",
},
});

// Step #3
// Create a new wallet from a mnemonic
const mnemonic = "end link visit estate sock hurt crucial forum eagle earn idle laptop wheat rookie when hard suffer duty kingdom clerk glide mechanic debris jar";
const mnemonic =
"end link visit estate sock hurt crucial forum eagle earn idle laptop wheat rookie when hard suffer duty kingdom clerk glide mechanic debris jar";
const entropy = mnemonicToEntropy(mnemonic, wordlist);
const masterkey = Bip32PrivateKey.fromBip39Entropy(Buffer.from(entropy), "");
const wallet = await HotWallet.fromMasterkey(masterkey.hex(), provider);
Expand All @@ -34,12 +44,15 @@ console.log("Wallet balance", (await wallet.getBalance()).toCore());

// Step #5
// Create a example transaction that sends 5 ADA to an address
const tx = await blaze.newTransaction()
.payLovelace(
Core.Address.fromBech32("addr_test1qrnrqg4s73skqfyyj69mzr7clpe8s7ux9t8z6l55x2f2xuqra34p9pswlrq86nq63hna7p4vkrcrxznqslkta9eqs2nsmlqvnk"),
5_000_000n
)
.complete();
const tx = await blaze
.newTransaction()
.payLovelace(
Core.Address.fromBech32(
"addr_test1qrnrqg4s73skqfyyj69mzr7clpe8s7ux9t8z6l55x2f2xuqra34p9pswlrq86nq63hna7p4vkrcrxznqslkta9eqs2nsmlqvnk",
),
5_000_000n,
)
.complete();

// Step #6
// Sign the transaction
Expand All @@ -50,4 +63,4 @@ const signexTx = await blaze.signTransaction(tx);
const txId = await blaze.provider.postTransactionToChain(signexTx);

// Optional: Print the transaction ID
console.log("Transaction ID", txId);
console.log("Transaction ID", txId);
74 changes: 44 additions & 30 deletions packages/blaze-query/src/u5c.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,16 +62,16 @@ export class U5C implements Provider {
}

async getUnspentOutputs(
address: Address
address: Address,
): Promise<TransactionUnspentOutput[]> {
const utxoSearchResult = await this.queryClient.searchUtxosByAddress(
new Uint8Array(Buffer.from(address.toBytes().toString(), "hex"))
new Uint8Array(Buffer.from(address.toBytes().toString(), "hex")),
);

const utxos = utxoSearchResult.map((item) => {
const input = new TransactionInput(
TransactionId(Buffer.from(item.txoRef.hash).toString("hex")),
BigInt(item.txoRef.index)
BigInt(item.txoRef.index),
);

const output = this._rpcTxOutToCoreTxOut(item.parsedValued!);
Expand All @@ -83,10 +83,10 @@ export class U5C implements Provider {

async getUnspentOutputsWithAsset(
address: Address,
unit: AssetId
unit: AssetId,
): Promise<TransactionUnspentOutput[]> {
const addressBytes = new Uint8Array(
Buffer.from(address.toBytes().toString(), "hex")
Buffer.from(address.toBytes().toString(), "hex"),
);

const unitBytes = new Uint8Array(Buffer.from(unit.toString(), "hex"));
Expand All @@ -95,13 +95,13 @@ export class U5C implements Provider {
await this.queryClient.searchUtxosByAddressWithAsset(
addressBytes,
undefined,
unitBytes
unitBytes,
);

return utxoSearchResult.map((item) => {
const input = new TransactionInput(
TransactionId(Buffer.from(item.txoRef.hash).toString("hex")),
BigInt(item.txoRef.index)
BigInt(item.txoRef.index),
);

const output = this._rpcTxOutToCoreTxOut(item.parsedValued!);
Expand All @@ -111,12 +111,12 @@ export class U5C implements Provider {
}

async getUnspentOutputByNFT(
unit: AssetId
unit: AssetId,
): Promise<TransactionUnspentOutput> {
const unitBytes = new Uint8Array(Buffer.from(unit.toString(), "hex"));
const utxoSearchResult = await this.queryClient.searchUtxosByAsset(
undefined,
unitBytes
unitBytes,
);

if (utxoSearchResult.length <= 0) {
Expand All @@ -130,7 +130,7 @@ export class U5C implements Provider {

const input = new TransactionInput(
TransactionId(Buffer.from(item.txoRef.hash).toString("hex")),
BigInt(item.txoRef.index)
BigInt(item.txoRef.index),
);

const output = this._rpcTxOutToCoreTxOut(item.parsedValued!);
Expand All @@ -139,11 +139,11 @@ export class U5C implements Provider {
}

async resolveUnspentOutputs(
txIns: TransactionInput[]
txIns: TransactionInput[],
): Promise<TransactionUnspentOutput[]> {
const references = txIns.map((txIn) => {
const txHashBytes = new Uint8Array(
Buffer.from(txIn.transactionId().toString(), "hex")
Buffer.from(txIn.transactionId().toString(), "hex"),
);
return {
txHash: txHashBytes,
Expand All @@ -156,7 +156,7 @@ export class U5C implements Provider {
utxoSearchResult?.map((item) => {
const input = new TransactionInput(
TransactionId(Buffer.from(item.txoRef.hash).toString("hex")),
BigInt(item.txoRef.index)
BigInt(item.txoRef.index),
);

const output = this._rpcTxOutToCoreTxOut(item.parsedValued!);
Expand All @@ -173,7 +173,7 @@ export class U5C implements Provider {

awaitTransactionConfirmation(
_txId: TransactionId,
_timeout?: number
_timeout?: number,
): Promise<boolean> {
throw new Error("Method not implemented.");
}
Expand All @@ -186,18 +186,18 @@ export class U5C implements Provider {

evaluateTransaction(
tx: Transaction,
additionalUtxos: TransactionUnspentOutput[]
additionalUtxos: TransactionUnspentOutput[],
): Promise<Redeemers> {
console.log("evaluateTransaction", tx, additionalUtxos);
throw new Error("Method not implemented.");
}

private _rpcTxOutToCoreTxOut(
rpcTxOutput: Cardano.TxOutput
rpcTxOutput: Cardano.TxOutput,
): TransactionOutput {
const output = new TransactionOutput(
Address.fromBytes(HexBlob.fromBytes(rpcTxOutput.address)),
this._rpcTxOutToCoreValue(rpcTxOutput)
this._rpcTxOutToCoreValue(rpcTxOutput),
);

if (rpcTxOutput.datum !== undefined) {
Expand All @@ -206,12 +206,14 @@ export class U5C implements Provider {
rpcTxOutput.datum.originalCbor.length > 0
) {
const inlineDatum = Datum.newInlineData(
PlutusData.fromCbor(HexBlob.fromBytes(rpcTxOutput.datum.originalCbor))
PlutusData.fromCbor(
HexBlob.fromBytes(rpcTxOutput.datum.originalCbor),
),
);
output.setDatum(inlineDatum);
} else if (rpcTxOutput.datum?.hash && rpcTxOutput.datum.hash.length > 0) {
const datumHash = Datum.newDataHash(
DatumHash(Buffer.from(rpcTxOutput.datum.hash).toString("hex"))
DatumHash(Buffer.from(rpcTxOutput.datum.hash).toString("hex")),
);
output.setDatum(datumHash);
}
Expand All @@ -222,16 +224,16 @@ export class U5C implements Provider {
const cbor = rpcTxOutput.script.script.value;
output.setScriptRef(
Script.newPlutusV1Script(
PlutusV1Script.fromCbor(HexBlob.fromBytes(cbor))
)
PlutusV1Script.fromCbor(HexBlob.fromBytes(cbor)),
),
);
}
if (rpcTxOutput.script.script.case === "plutusV2") {
const cbor = rpcTxOutput.script.script.value;
output.setScriptRef(
Script.newPlutusV2Script(
PlutusV2Script.fromCbor(HexBlob.fromBytes(cbor))
)
PlutusV2Script.fromCbor(HexBlob.fromBytes(cbor)),
),
);
}
}
Expand All @@ -242,19 +244,19 @@ export class U5C implements Provider {
private _rpcTxOutToCoreValue(rpcTxOutput: Cardano.TxOutput): Value {
return new Value(
BigInt(rpcTxOutput.coin),
this._rpcMultiAssetOutputToTokenMap(rpcTxOutput.assets)
this._rpcMultiAssetOutputToTokenMap(rpcTxOutput.assets),
);
}

private _rpcMultiAssetOutputToTokenMap(
multiAsset: Cardano.Multiasset[]
multiAsset: Cardano.Multiasset[],
): TokenMap {
const tokenMap: TokenMap = new Map();
multiAsset.forEach((ma) => {
ma.assets.forEach((asset) => {
const assetId = AssetId.fromParts(
PolicyId(Buffer.from(ma.policyId).toString("hex")),
AssetName(Buffer.from(asset.name).toString("hex"))
AssetName(Buffer.from(asset.name).toString("hex")),
);

const quantity = BigInt(asset.outputCoin);
Expand All @@ -270,20 +272,32 @@ export class U5C implements Provider {
}

private _rpcPParamsToCorePParams(
rpcPParams: Cardano.PParams
rpcPParams: Cardano.PParams,
): ProtocolParameters {
return {
coinsPerUtxoByte: Number(rpcPParams.coinsPerUtxoByte),
costModels: (new Map() as CostModels)
.set(
PlutusLanguageVersion.V1,
rpcPParams.costModels?.plutusV1?.values.map(v => Number(v.toString())) ?? hardCodedProtocolParams.costModels.get(PlutusLanguageVersion.V1) ?? []
rpcPParams.costModels?.plutusV1?.values.map((v) =>
Number(v.toString()),
) ??
hardCodedProtocolParams.costModels.get(PlutusLanguageVersion.V1) ??
[],
)
.set(
PlutusLanguageVersion.V2,
rpcPParams.costModels?.plutusV2?.values.map(v => Number(v.toString())) ?? hardCodedProtocolParams.costModels.get(PlutusLanguageVersion.V2) ?? []
rpcPParams.costModels?.plutusV2?.values.map((v) =>
Number(v.toString()),
) ??
hardCodedProtocolParams.costModels.get(PlutusLanguageVersion.V2) ??
[],
)
.set(PlutusLanguageVersion.V3, hardCodedProtocolParams.costModels.get(PlutusLanguageVersion.V3) ?? []),
.set(
PlutusLanguageVersion.V3,
hardCodedProtocolParams.costModels.get(PlutusLanguageVersion.V3) ??
[],
),
maxBlockBodySize: Number(rpcPParams.maxBlockBodySize),
maxBlockHeaderSize: Number(rpcPParams.maxBlockHeaderSize),
maxCollateralInputs: Number(rpcPParams.maxCollateralInputs),
Expand Down

0 comments on commit 4a2c0a0

Please sign in to comment.