|
| 1 | +// Copyright 2020-2025 IOTA Stiftung |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +import { IdentityClient, IotaDocument } from "@iota/identity-wasm/node"; |
| 5 | +import { IotaClient } from "@iota/iota-sdk/client"; |
| 6 | +import { TransactionDataBuilder } from "@iota/iota-sdk/transactions"; |
| 7 | +import { getFundedClient, getMemstorage, NETWORK_URL } from "../util"; |
| 8 | + |
| 9 | +/** |
| 10 | + * This example demonstrates: |
| 11 | + * 1. A user - Alice - can build a transaction that is sponsored by another user - Bob; |
| 12 | + * 2. Deconstruct the transaction into its parts, to execute it manually through the SDK's IotaClient; |
| 13 | + * 3. Apply the transaction's off-chain effects, from its on-chain ones. |
| 14 | + */ |
| 15 | +export async function advancedTransaction(): Promise<void> { |
| 16 | + const aliceStorage = getMemstorage(); |
| 17 | + const aliceClient = await getFundedClient(aliceStorage); |
| 18 | + |
| 19 | + const bobStorage = getMemstorage(); |
| 20 | + const bobClient = await getFundedClient(bobStorage); |
| 21 | + |
| 22 | + const [txDataBcs, signatures, tx] = await aliceClient |
| 23 | + .createIdentity(new IotaDocument(aliceClient.network())) |
| 24 | + .finish() |
| 25 | + .withSender(aliceClient.senderAddress()) |
| 26 | + .withSponsor(aliceClient.readOnly(), (tx_data: TransactionDataBuilder) => bobSponsorFn(tx_data, bobClient)) |
| 27 | + .then(txBuilder => txBuilder.build(aliceClient)); |
| 28 | + |
| 29 | + // create new client to connect to IOTA network |
| 30 | + const iotaClient = new IotaClient({ url: NETWORK_URL }); |
| 31 | + const tx_response = await iotaClient.executeTransactionBlock({ |
| 32 | + transactionBlock: txDataBcs, |
| 33 | + signature: signatures, |
| 34 | + options: { showEffects: true }, |
| 35 | + }); |
| 36 | + await iotaClient.waitForTransaction({ digest: tx_response.digest }); |
| 37 | + |
| 38 | + const identity = await tx.apply(tx_response.effects!, aliceClient.readOnly()); |
| 39 | + |
| 40 | + console.log(`Alice successfully created Identity ${identity.id()}! Thanks for the gas Bob!`); |
| 41 | +} |
| 42 | + |
| 43 | +async function bobSponsorFn(tx_data: TransactionDataBuilder, client: IdentityClient): Promise<string> { |
| 44 | + const coin = await client.iotaClient().getCoins({ owner: client.senderAddress(), coinType: "0x2::iota::IOTA" }) |
| 45 | + .then(res => res.data[0]); |
| 46 | + tx_data.gasData.owner = client.senderAddress(); |
| 47 | + tx_data.gasData.price = 1000; |
| 48 | + tx_data.gasData.budget = 50000000; |
| 49 | + tx_data.gasData.payment = [{ version: coin.version, objectId: coin.coinObjectId, digest: coin.digest }]; |
| 50 | + |
| 51 | + return await client.signer().sign(tx_data.build()); |
| 52 | +} |
0 commit comments