From c8f9c53a044b30e4ac4f7440281a3acbceb67699 Mon Sep 17 00:00:00 2001 From: Chad Ostrowski <221614+chadoh@users.noreply.github.com> Date: Wed, 13 Mar 2024 11:25:16 -0400 Subject: [PATCH] feat(ts-bindings)!: now powered by ContractClient MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Most logic in the TS Bindings has now been implemented in stellar-sdk as a `ContractClient` that dynamically fetches the contract's XDR and generates JS for each contract method at runtime. This means logic like `AssembledTransaction` now lives entirely in stellar-sdk, and can be relied on by each library generated by TS Bindings, rather than duplicating this logic in each of these libraries. TS Bindings now has a much smaller focus—basically, only to generate the types. This shrinks the TS Bindings, importing and using this new ContractClient logic. --- Cargo.lock | 8 +- .../dist/cjs/assembled-tx.d.ts | 184 --- .../dist/cjs/assembled-tx.js | 462 ------ .../test_custom_types/dist/cjs/index.d.ts | 544 ++++--- .../test_custom_types/dist/cjs/index.js | 434 +----- .../dist/cjs/method-options.d.ts | 47 - .../dist/cjs/method-options.js | 4 - .../dist/esm/assembled-tx.d.ts | 184 --- .../dist/esm/assembled-tx.js | 450 ------ .../test_custom_types/dist/esm/index.d.ts | 544 ++++--- .../test_custom_types/dist/esm/index.js | 432 +----- .../dist/esm/method-options.d.ts | 47 - .../dist/esm/method-options.js | 3 - .../dist/types/assembled-tx.d.ts | 184 --- .../test_custom_types/dist/types/index.d.ts | 544 ++++--- .../dist/types/method-options.d.ts | 47 - .../test_custom_types/package-lock.json | 59 +- .../fixtures/test_custom_types/package.json | 4 +- .../test_custom_types/src/assembled-tx.ts | 664 --------- .../fixtures/test_custom_types/src/index.ts | 1307 ++++++++--------- .../test_custom_types/src/method-options.ts | 50 - .../src/boilerplate.rs | 34 +- cmd/crates/soroban-spec-typescript/src/lib.rs | 189 +-- .../src/project_template/package.json | 2 +- .../src/project_template/src/assembled-tx.ts | 664 --------- .../src/project_template/src/index.ts | 18 +- .../project_template/src/method-options.ts | 50 - .../soroban-spec-typescript/ts-tests/.env | 1 + .../ts-tests/package-lock.json | 386 +++-- .../ts-tests/package.json | 2 +- .../ts-tests/src/test-custom-types.ts | 30 +- .../src/test-deserialized-transaction.ts | 12 +- .../ts-tests/src/test-hello-world.ts | 12 +- .../ts-tests/src/test-methods-as-args.ts | 12 +- .../ts-tests/src/test-swap.ts | 20 +- .../ts-tests/src/util.ts | 36 +- cmd/soroban-cli/Cargo.toml | 2 +- 37 files changed, 2205 insertions(+), 5467 deletions(-) delete mode 100644 cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/assembled-tx.d.ts delete mode 100644 cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/assembled-tx.js delete mode 100644 cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/method-options.d.ts delete mode 100644 cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/method-options.js delete mode 100644 cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/assembled-tx.d.ts delete mode 100644 cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/assembled-tx.js delete mode 100644 cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/method-options.d.ts delete mode 100644 cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/method-options.js delete mode 100644 cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/types/assembled-tx.d.ts delete mode 100644 cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/types/method-options.d.ts delete mode 100644 cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/src/assembled-tx.ts delete mode 100644 cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/src/method-options.ts delete mode 100644 cmd/crates/soroban-spec-typescript/src/project_template/src/assembled-tx.ts delete mode 100644 cmd/crates/soroban-spec-typescript/src/project_template/src/method-options.ts diff --git a/Cargo.lock b/Cargo.lock index c126a7fac6..f78197cf67 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2011,6 +2011,12 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "hermit-abi" version = "0.3.6" @@ -3610,7 +3616,7 @@ dependencies = [ "ethnum", "futures-util", "gix", - "heck 0.4.1", + "heck 0.5.0", "hex", "home", "http 0.2.11", diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/assembled-tx.d.ts b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/assembled-tx.d.ts deleted file mode 100644 index 1d5e6f5ee8..0000000000 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/assembled-tx.d.ts +++ /dev/null @@ -1,184 +0,0 @@ -import { Account, Address, Operation, SorobanRpc, xdr } from "@stellar/stellar-sdk"; -import type { Memo, MemoType, Transaction } from "@stellar/stellar-sdk"; -import type { ClassOptions, MethodOptions, Wallet, XDR_BASE64 } from "./method-options.js"; -export type Tx = Transaction, Operation[]>; -export declare class ExpiredStateError extends Error { -} -export declare class NeedsMoreSignaturesError extends Error { -} -export declare class WalletDisconnectedError extends Error { -} -export declare class SendResultOnlyError extends Error { -} -export declare class SendFailedError extends Error { -} -export declare class NoUnsignedNonInvokerAuthEntriesError extends Error { -} -type SendTx = SorobanRpc.Api.SendTransactionResponse; -type GetTx = SorobanRpc.Api.GetTransactionResponse; -export type u32 = number; -export type i32 = number; -export type u64 = bigint; -export type i64 = bigint; -export type u128 = bigint; -export type i128 = bigint; -export type u256 = bigint; -export type i256 = bigint; -export type Option = T | undefined; -export type Typepoint = bigint; -export type Duration = bigint; -export { Address }; -export interface Error_ { - message: string; -} -export interface Result { - unwrap(): T; - unwrapErr(): E; - isOk(): boolean; - isErr(): boolean; -} -export declare class Ok implements Result { - readonly value: T; - constructor(value: T); - unwrapErr(): E; - unwrap(): T; - isOk(): boolean; - isErr(): boolean; -} -export declare class Err implements Result { - readonly error: E; - constructor(error: E); - unwrapErr(): E; - unwrap(): never; - isOk(): boolean; - isErr(): boolean; -} -export declare const contractErrorPattern: RegExp; -type AssembledTransactionOptions = MethodOptions & ClassOptions & { - method: string; - args?: any[]; - parseResultXdr: (xdr: string | xdr.ScVal | Err) => T; -}; -export declare const NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; -export declare class AssembledTransaction { - options: AssembledTransactionOptions; - raw: Tx; - private simulation?; - private simulationResult?; - private simulationTransactionData?; - private server; - toJSON(): string; - static fromJSON(options: Omit, 'args'>, { tx, simulationResult, simulationTransactionData }: { - tx: XDR_BASE64; - simulationResult: { - auth: XDR_BASE64[]; - retval: XDR_BASE64; - }; - simulationTransactionData: XDR_BASE64; - }): AssembledTransaction; - private constructor(); - static fromSimulation(options: AssembledTransactionOptions): Promise>; - simulate: () => Promise; - get simulationData(): { - result: SorobanRpc.Api.SimulateHostFunctionResult; - transactionData: xdr.SorobanTransactionData; - }; - get result(): T; - parseError(errorMessage: string): Err | undefined; - getWallet: () => Promise; - getPublicKey: () => Promise; - /** - * Get account details from the Soroban network for the publicKey currently - * selected in user's wallet. If not connected to Freighter, use placeholder - * null account. - */ - getAccount: () => Promise; - /** - * Sign the transaction with the `wallet` (default Freighter), then send to - * the network and return a `SentTransaction` that keeps track of all the - * attempts to send and fetch the transaction from the network. - */ - signAndSend: ({ secondsToWait, force }?: { - /** - * Wait `secondsToWait` seconds (default: 10) for both the transaction to SEND successfully (will keep trying if the server returns `TRY_AGAIN_LATER`), as well as for the transaction to COMPLETE (will keep checking if the server returns `PENDING`). - */ - secondsToWait?: number | undefined; - /** - * If `true`, sign and send the transaction even if it is a read call. - */ - force?: boolean | undefined; - }) => Promise>; - getStorageExpiration: () => Promise; - /** - * Get a list of accounts, other than the invoker of the simulation, that - * need to sign auth entries in this transaction. - * - * Soroban allows multiple people to sign a transaction. Someone needs to - * sign the final transaction envelope; this person/account is called the - * _invoker_, or _source_. Other accounts might need to sign individual auth - * entries in the transaction, if they're not also the invoker. - * - * This function returns a list of accounts that need to sign auth entries, - * assuming that the same invoker/source account will sign the final - * transaction envelope as signed the initial simulation. - * - * One at a time, for each public key in this array, you will need to - * serialize this transaction with `toJSON`, send to the owner of that key, - * deserialize the transaction with `txFromJson`, and call - * {@link signAuthEntries}. Then re-serialize and send to the next account - * in this list. - */ - needsNonInvokerSigningBy: ({ includeAlreadySigned, }?: { - /** - * Whether or not to include auth entries that have already been signed. Default: false - */ - includeAlreadySigned?: boolean | undefined; - }) => Promise; - preImageFor(entry: xdr.SorobanAuthorizationEntry, signatureExpirationLedger: number): xdr.HashIdPreimage; - /** - * If {@link needsNonInvokerSigningBy} returns a non-empty list, you can serialize - * the transaction with `toJSON`, send it to the owner of one of the public keys - * in the map, deserialize with `txFromJSON`, and call this method on their - * machine. Internally, this will use `signAuthEntry` function from connected - * `wallet` for each. - * - * Then, re-serialize the transaction and either send to the next - * `needsNonInvokerSigningBy` owner, or send it back to the original account - * who simulated the transaction so they can {@link sign} the transaction - * envelope and {@link send} it to the network. - * - * Sending to all `needsNonInvokerSigningBy` owners in parallel is not currently - * supported! - */ - signAuthEntries: (expiration?: number | Promise) => Promise; - get isReadCall(): boolean; - hasRealInvoker: () => Promise; -} -/** - * A transaction that has been sent to the Soroban network. This happens in two steps: - * - * 1. `sendTransaction`: initial submission of the transaction to the network. - * This step can run into problems, and will be retried with exponential - * backoff if it does. See all attempts in `sendTransactionResponseAll` and the - * most recent attempt in `sendTransactionResponse`. - * 2. `getTransaction`: once the transaction has been submitted to the network - * successfully, you need to wait for it to finalize to get the results of the - * transaction. This step can also run into problems, and will be retried with - * exponential backoff if it does. See all attempts in - * `getTransactionResponseAll` and the most recent attempt in - * `getTransactionResponse`. - */ -declare class SentTransaction { - options: AssembledTransactionOptions; - assembled: AssembledTransaction; - server: SorobanRpc.Server; - signed: Tx; - sendTransactionResponse?: SendTx; - sendTransactionResponseAll?: SendTx[]; - getTransactionResponse?: GetTx; - getTransactionResponseAll?: GetTx[]; - constructor(options: AssembledTransactionOptions, assembled: AssembledTransaction); - static init: (options: AssembledTransactionOptions, assembled: AssembledTransaction, secondsToWait?: number) => Promise>; - private send; - get result(): T; -} diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/assembled-tx.js b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/assembled-tx.js deleted file mode 100644 index c60a6e5f89..0000000000 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/assembled-tx.js +++ /dev/null @@ -1,462 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AssembledTransaction = exports.NULL_ACCOUNT = exports.contractErrorPattern = exports.Err = exports.Ok = exports.Address = exports.NoUnsignedNonInvokerAuthEntriesError = exports.SendFailedError = exports.SendResultOnlyError = exports.WalletDisconnectedError = exports.NeedsMoreSignaturesError = exports.ExpiredStateError = void 0; -const stellar_sdk_1 = require("@stellar/stellar-sdk"); -Object.defineProperty(exports, "Address", { enumerable: true, get: function () { return stellar_sdk_1.Address; } }); -const buffer_1 = require("buffer"); -class ExpiredStateError extends Error { -} -exports.ExpiredStateError = ExpiredStateError; -class NeedsMoreSignaturesError extends Error { -} -exports.NeedsMoreSignaturesError = NeedsMoreSignaturesError; -class WalletDisconnectedError extends Error { -} -exports.WalletDisconnectedError = WalletDisconnectedError; -class SendResultOnlyError extends Error { -} -exports.SendResultOnlyError = SendResultOnlyError; -class SendFailedError extends Error { -} -exports.SendFailedError = SendFailedError; -class NoUnsignedNonInvokerAuthEntriesError extends Error { -} -exports.NoUnsignedNonInvokerAuthEntriesError = NoUnsignedNonInvokerAuthEntriesError; -; -; -class Ok { - value; - constructor(value) { - this.value = value; - } - unwrapErr() { - throw new Error('No error'); - } - unwrap() { - return this.value; - } - isOk() { - return true; - } - isErr() { - return !this.isOk(); - } -} -exports.Ok = Ok; -class Err { - error; - constructor(error) { - this.error = error; - } - unwrapErr() { - return this.error; - } - unwrap() { - throw new Error(this.error.message); - } - isOk() { - return false; - } - isErr() { - return !this.isOk(); - } -} -exports.Err = Err; -exports.contractErrorPattern = /Error\(Contract, #(\d+)\)/; -exports.NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; -class AssembledTransaction { - options; - raw; - simulation; - simulationResult; - simulationTransactionData; - server; - toJSON() { - return JSON.stringify({ - method: this.options.method, - tx: this.raw?.toXDR(), - simulationResult: { - auth: this.simulationData.result.auth.map(a => a.toXDR('base64')), - retval: this.simulationData.result.retval.toXDR('base64'), - }, - simulationTransactionData: this.simulationData.transactionData.toXDR('base64'), - }); - } - static fromJSON(options, { tx, simulationResult, simulationTransactionData }) { - const txn = new AssembledTransaction(options); - txn.raw = stellar_sdk_1.TransactionBuilder.fromXDR(tx, options.networkPassphrase); - txn.simulationResult = { - auth: simulationResult.auth.map(a => stellar_sdk_1.xdr.SorobanAuthorizationEntry.fromXDR(a, 'base64')), - retval: stellar_sdk_1.xdr.ScVal.fromXDR(simulationResult.retval, 'base64'), - }; - txn.simulationTransactionData = stellar_sdk_1.xdr.SorobanTransactionData.fromXDR(simulationTransactionData, 'base64'); - return txn; - } - constructor(options) { - this.options = options; - this.server = new stellar_sdk_1.SorobanRpc.Server(this.options.rpcUrl, { - allowHttp: this.options.rpcUrl.startsWith("http://"), - }); - } - static async fromSimulation(options) { - const tx = new AssembledTransaction(options); - const contract = new stellar_sdk_1.Contract(options.contractId); - tx.raw = new stellar_sdk_1.TransactionBuilder(await tx.getAccount(), { - fee: options.fee?.toString(10) ?? stellar_sdk_1.BASE_FEE, - networkPassphrase: options.networkPassphrase, - }) - .addOperation(contract.call(options.method, ...(options.args ?? []))) - .setTimeout(stellar_sdk_1.TimeoutInfinite) - .build(); - return await tx.simulate(); - } - simulate = async () => { - if (!this.raw) - throw new Error('Transaction has not yet been assembled'); - this.simulation = await this.server.simulateTransaction(this.raw); - if (stellar_sdk_1.SorobanRpc.Api.isSimulationSuccess(this.simulation)) { - this.raw = stellar_sdk_1.SorobanRpc.assembleTransaction(this.raw, this.simulation).build(); - } - return this; - }; - get simulationData() { - if (this.simulationResult && this.simulationTransactionData) { - return { - result: this.simulationResult, - transactionData: this.simulationTransactionData, - }; - } - // else, we know we just did the simulation on this machine - const simulation = this.simulation; - if (stellar_sdk_1.SorobanRpc.Api.isSimulationError(simulation)) { - throw new Error(`Transaction simulation failed: "${simulation.error}"`); - } - if (stellar_sdk_1.SorobanRpc.Api.isSimulationRestore(simulation)) { - throw new ExpiredStateError(`You need to restore some contract state before you can invoke this method. ${JSON.stringify(simulation, null, 2)}`); - } - if (!simulation.result) { - throw new Error(`Expected an invocation simulation, but got no 'result' field. Simulation: ${JSON.stringify(simulation, null, 2)}`); - } - // add to object for serialization & deserialization - this.simulationResult = simulation.result; - this.simulationTransactionData = simulation.transactionData.build(); - return { - result: this.simulationResult, - transactionData: this.simulationTransactionData, - }; - } - get result() { - try { - return this.options.parseResultXdr(this.simulationData.result.retval); - } - catch (e) { - let err = this.parseError(e.toString()); - if (err) - return err; - throw e; - } - } - parseError(errorMessage) { - if (!this.options.errorTypes) - return; - const match = errorMessage.match(exports.contractErrorPattern); - if (!match) - return; - let i = parseInt(match[1], 10); - let err = this.options.errorTypes[i]; - if (err) - return new Err(err); - } - getWallet = async () => { - return this.options.wallet ?? (await Promise.resolve().then(() => require("@stellar/freighter-api"))).default; - }; - getPublicKey = async () => { - const wallet = await this.getWallet(); - if (await wallet.isConnected() && await wallet.isAllowed()) { - return (await wallet.getUserInfo()).publicKey; - } - }; - /** - * Get account details from the Soroban network for the publicKey currently - * selected in user's wallet. If not connected to Freighter, use placeholder - * null account. - */ - getAccount = async () => { - const publicKey = await this.getPublicKey(); - return publicKey - ? await this.server.getAccount(publicKey) - : new stellar_sdk_1.Account(exports.NULL_ACCOUNT, "0"); - }; - /** - * Sign the transaction with the `wallet` (default Freighter), then send to - * the network and return a `SentTransaction` that keeps track of all the - * attempts to send and fetch the transaction from the network. - */ - signAndSend = async ({ secondsToWait = 10, force = false } = {}) => { - if (!this.raw) { - throw new Error('Transaction has not yet been simulated'); - } - if (!force && this.isReadCall) { - throw new Error('This is a read call. It requires no signature or sending. Use `force: true` to sign and send anyway.'); - } - if (!await this.hasRealInvoker()) { - throw new WalletDisconnectedError('Wallet is not connected'); - } - if (this.raw.source !== (await this.getAccount()).accountId()) { - throw new Error(`You must submit the transaction with the account that originally created it. Please switch to the wallet with "${this.raw.source}" as its public key.`); - } - if ((await this.needsNonInvokerSigningBy()).length) { - throw new NeedsMoreSignaturesError('Transaction requires more signatures. See `needsNonInvokerSigningBy` for details.'); - } - return await SentTransaction.init(this.options, this, secondsToWait); - }; - getStorageExpiration = async () => { - const entryRes = await this.server.getLedgerEntries(new stellar_sdk_1.Contract(this.options.contractId).getFootprint()); - if (!entryRes.entries || - !entryRes.entries.length || - !entryRes.entries[0].liveUntilLedgerSeq) - throw new Error('failed to get ledger entry'); - return entryRes.entries[0].liveUntilLedgerSeq; - }; - /** - * Get a list of accounts, other than the invoker of the simulation, that - * need to sign auth entries in this transaction. - * - * Soroban allows multiple people to sign a transaction. Someone needs to - * sign the final transaction envelope; this person/account is called the - * _invoker_, or _source_. Other accounts might need to sign individual auth - * entries in the transaction, if they're not also the invoker. - * - * This function returns a list of accounts that need to sign auth entries, - * assuming that the same invoker/source account will sign the final - * transaction envelope as signed the initial simulation. - * - * One at a time, for each public key in this array, you will need to - * serialize this transaction with `toJSON`, send to the owner of that key, - * deserialize the transaction with `txFromJson`, and call - * {@link signAuthEntries}. Then re-serialize and send to the next account - * in this list. - */ - needsNonInvokerSigningBy = async ({ includeAlreadySigned = false, } = {}) => { - if (!this.raw) { - throw new Error('Transaction has not yet been simulated'); - } - // We expect that any transaction constructed by these libraries has a - // single operation, which is an InvokeHostFunction operation. The host - // function being invoked is the contract method call. - if (!("operations" in this.raw)) { - throw new Error(`Unexpected Transaction type; no operations: ${JSON.stringify(this.raw)}`); - } - const rawInvokeHostFunctionOp = this.raw - .operations[0]; - return [...new Set((rawInvokeHostFunctionOp.auth ?? []).filter(entry => entry.credentials().switch() === - stellar_sdk_1.xdr.SorobanCredentialsType.sorobanCredentialsAddress() && - (includeAlreadySigned || - entry.credentials().address().signature().switch().name === 'scvVoid')).map(entry => stellar_sdk_1.StrKey.encodeEd25519PublicKey(entry.credentials().address().address().accountId().ed25519())))]; - }; - preImageFor(entry, signatureExpirationLedger) { - const addrAuth = entry.credentials().address(); - return stellar_sdk_1.xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(new stellar_sdk_1.xdr.HashIdPreimageSorobanAuthorization({ - networkId: (0, stellar_sdk_1.hash)(buffer_1.Buffer.from(this.options.networkPassphrase)), - nonce: addrAuth.nonce(), - invocation: entry.rootInvocation(), - signatureExpirationLedger, - })); - } - /** - * If {@link needsNonInvokerSigningBy} returns a non-empty list, you can serialize - * the transaction with `toJSON`, send it to the owner of one of the public keys - * in the map, deserialize with `txFromJSON`, and call this method on their - * machine. Internally, this will use `signAuthEntry` function from connected - * `wallet` for each. - * - * Then, re-serialize the transaction and either send to the next - * `needsNonInvokerSigningBy` owner, or send it back to the original account - * who simulated the transaction so they can {@link sign} the transaction - * envelope and {@link send} it to the network. - * - * Sending to all `needsNonInvokerSigningBy` owners in parallel is not currently - * supported! - */ - signAuthEntries = async ( - /** - * When to set each auth entry to expire. Could be any number of blocks in - * the future. Can be supplied as a promise or a raw number. Default: - * contract's current `persistent` storage expiration date/ledger - * number/block. - */ - expiration = this.getStorageExpiration()) => { - if (!this.raw) - throw new Error('Transaction has not yet been assembled or simulated'); - const needsNonInvokerSigningBy = await this.needsNonInvokerSigningBy(); - if (!needsNonInvokerSigningBy) - throw new NoUnsignedNonInvokerAuthEntriesError('No unsigned non-invoker auth entries; maybe you already signed?'); - const publicKey = await this.getPublicKey(); - if (!publicKey) - throw new Error('Could not get public key from wallet; maybe Freighter is not signed in?'); - if (needsNonInvokerSigningBy.indexOf(publicKey) === -1) - throw new Error(`No auth entries for public key "${publicKey}"`); - const wallet = await this.getWallet(); - const rawInvokeHostFunctionOp = this.raw - .operations[0]; - const authEntries = rawInvokeHostFunctionOp.auth ?? []; - for (const [i, entry] of authEntries.entries()) { - if (entry.credentials().switch() !== - stellar_sdk_1.xdr.SorobanCredentialsType.sorobanCredentialsAddress()) { - // if the invoker/source account, then the entry doesn't need explicit - // signature, since the tx envelope is already signed by the source - // account, so only check for sorobanCredentialsAddress - continue; - } - const pk = stellar_sdk_1.StrKey.encodeEd25519PublicKey(entry.credentials().address().address().accountId().ed25519()); - // this auth entry needs to be signed by a different account - // (or maybe already was!) - if (pk !== publicKey) - continue; - authEntries[i] = await (0, stellar_sdk_1.authorizeEntry)(entry, async (preimage) => buffer_1.Buffer.from(await wallet.signAuthEntry(preimage.toXDR('base64')), 'base64'), await expiration, this.options.networkPassphrase); - } - }; - get isReadCall() { - const authsCount = this.simulationData.result.auth.length; - const writeLength = this.simulationData.transactionData.resources().footprint().readWrite().length; - return (authsCount === 0) && (writeLength === 0); - } - hasRealInvoker = async () => { - const account = await this.getAccount(); - return account.accountId() !== exports.NULL_ACCOUNT; - }; -} -exports.AssembledTransaction = AssembledTransaction; -/** - * A transaction that has been sent to the Soroban network. This happens in two steps: - * - * 1. `sendTransaction`: initial submission of the transaction to the network. - * This step can run into problems, and will be retried with exponential - * backoff if it does. See all attempts in `sendTransactionResponseAll` and the - * most recent attempt in `sendTransactionResponse`. - * 2. `getTransaction`: once the transaction has been submitted to the network - * successfully, you need to wait for it to finalize to get the results of the - * transaction. This step can also run into problems, and will be retried with - * exponential backoff if it does. See all attempts in - * `getTransactionResponseAll` and the most recent attempt in - * `getTransactionResponse`. - */ -class SentTransaction { - options; - assembled; - server; - signed; - sendTransactionResponse; - sendTransactionResponseAll; - getTransactionResponse; - getTransactionResponseAll; - constructor(options, assembled) { - this.options = options; - this.assembled = assembled; - this.server = new stellar_sdk_1.SorobanRpc.Server(this.options.rpcUrl, { - allowHttp: this.options.rpcUrl.startsWith("http://"), - }); - this.assembled = assembled; - } - static init = async (options, assembled, secondsToWait = 10) => { - const tx = new SentTransaction(options, assembled); - return await tx.send(secondsToWait); - }; - send = async (secondsToWait = 10) => { - const wallet = await this.assembled.getWallet(); - this.sendTransactionResponseAll = await withExponentialBackoff(async (previousFailure) => { - if (previousFailure) { - // Increment transaction sequence number and resimulate before trying again - // Soroban transaction can only have 1 operation - const op = this.assembled.raw.operations[0]; - this.assembled.raw = new stellar_sdk_1.TransactionBuilder(await this.assembled.getAccount(), { - fee: this.assembled.raw.fee, - networkPassphrase: this.options.networkPassphrase, - }) - .setTimeout(stellar_sdk_1.TimeoutInfinite) - .addOperation(stellar_sdk_1.Operation.invokeHostFunction({ ...op, auth: op.auth ?? [] })) - .build(); - await this.assembled.simulate(); - } - const signature = await wallet.signTransaction(this.assembled.raw.toXDR(), { - networkPassphrase: this.options.networkPassphrase, - }); - this.signed = stellar_sdk_1.TransactionBuilder.fromXDR(signature, this.options.networkPassphrase); - return this.server.sendTransaction(this.signed); - }, resp => resp.status !== "PENDING", secondsToWait); - this.sendTransactionResponse = this.sendTransactionResponseAll[this.sendTransactionResponseAll.length - 1]; - if (this.sendTransactionResponse.status !== "PENDING") { - throw new Error(`Tried to resubmit transaction for ${secondsToWait} seconds, but it's still failing. ` + - `All attempts: ${JSON.stringify(this.sendTransactionResponseAll, null, 2)}`); - } - const { hash } = this.sendTransactionResponse; - this.getTransactionResponseAll = await withExponentialBackoff(() => this.server.getTransaction(hash), resp => resp.status === stellar_sdk_1.SorobanRpc.Api.GetTransactionStatus.NOT_FOUND, secondsToWait); - this.getTransactionResponse = this.getTransactionResponseAll[this.getTransactionResponseAll.length - 1]; - if (this.getTransactionResponse.status === stellar_sdk_1.SorobanRpc.Api.GetTransactionStatus.NOT_FOUND) { - console.error(`Waited ${secondsToWait} seconds for transaction to complete, but it did not. ` + - `Returning anyway. Check the transaction status manually. ` + - `Sent transaction: ${JSON.stringify(this.sendTransactionResponse, null, 2)}\n` + - `All attempts to get the result: ${JSON.stringify(this.getTransactionResponseAll, null, 2)}`); - } - return this; - }; - get result() { - // 1. check if transaction was submitted and awaited with `getTransaction` - if ("getTransactionResponse" in this && - this.getTransactionResponse) { - // getTransactionResponse has a `returnValue` field unless it failed - if ("returnValue" in this.getTransactionResponse) { - return this.options.parseResultXdr(this.getTransactionResponse.returnValue); - } - // if "returnValue" not present, the transaction failed; return without parsing the result - throw new Error("Transaction failed! Cannot parse result."); - } - // 2. otherwise, maybe it was merely sent with `sendTransaction` - if (this.sendTransactionResponse) { - const errorResult = this.sendTransactionResponse.errorResult?.result(); - if (errorResult) { - throw new SendFailedError(`Transaction simulation looked correct, but attempting to send the transaction failed. Check \`simulation\` and \`sendTransactionResponseAll\` to troubleshoot. Decoded \`sendTransactionResponse.errorResultXdr\`: ${errorResult}`); - } - throw new SendResultOnlyError(`Transaction was sent to the network, but not yet awaited. No result to show. Await transaction completion with \`getTransaction(sendTransactionResponse.hash)\``); - } - // 3. finally, if neither of those are present, throw an error - throw new Error(`Sending transaction failed: ${JSON.stringify(this.assembled)}`); - } -} -/** - * Keep calling a `fn` for `secondsToWait` seconds, if `keepWaitingIf` is true. - * Returns an array of all attempts to call the function. - */ -async function withExponentialBackoff(fn, keepWaitingIf, secondsToWait, exponentialFactor = 1.5, verbose = false) { - const attempts = []; - let count = 0; - attempts.push(await fn()); - if (!keepWaitingIf(attempts[attempts.length - 1])) - return attempts; - const waitUntil = new Date(Date.now() + secondsToWait * 1000).valueOf(); - let waitTime = 1000; - let totalWaitTime = waitTime; - while (Date.now() < waitUntil && keepWaitingIf(attempts[attempts.length - 1])) { - count++; - // Wait a beat - if (verbose) { - console.info(`Waiting ${waitTime}ms before trying again (bringing the total wait time to ${totalWaitTime}ms so far, of total ${secondsToWait * 1000}ms)`); - } - await new Promise(res => setTimeout(res, waitTime)); - // Exponential backoff - waitTime = waitTime * exponentialFactor; - if (new Date(Date.now() + waitTime).valueOf() > waitUntil) { - waitTime = waitUntil - Date.now(); - if (verbose) { - console.info(`was gonna wait too long; new waitTime: ${waitTime}ms`); - } - } - totalWaitTime = waitTime + totalWaitTime; - // Try again - attempts.push(await fn(attempts[attempts.length - 1])); - if (verbose && keepWaitingIf(attempts[attempts.length - 1])) { - console.info(`${count}. Called ${fn}; ${attempts.length} prev attempts. Most recent: ${JSON.stringify(attempts[attempts.length - 1], null, 2)}`); - } - } - return attempts; -} diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/index.d.ts b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/index.d.ts index 66d3d59597..58a5712000 100644 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/index.d.ts +++ b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/index.d.ts @@ -1,10 +1,10 @@ -import { ContractSpec } from '@stellar/stellar-sdk'; import { Buffer } from "buffer"; -import { AssembledTransaction, Ok, Err } from './assembled-tx.js'; -import type { u32, i32, i64, i128, Option, Error_ } from './assembled-tx.js'; -import type { ClassOptions } from './method-options.js'; -export * from './assembled-tx.js'; -export * from './method-options.js'; +import { AssembledTransaction, ContractClient, ContractClientOptions } from '@stellar/stellar-sdk/lib/contract_client/index.js'; +import type { u32, i32, i64, u128, i128, u256, i256, Option } from '@stellar/stellar-sdk/lib/contract_client'; +import { Result } from '@stellar/stellar-sdk/lib/rust_types/index.js'; +export * from '@stellar/stellar-sdk'; +export * from '@stellar/stellar-sdk/lib/contract_client/index.js'; +export * from '@stellar/stellar-sdk/lib/rust_types/index.js'; export declare const networks: { readonly futurenet: { readonly networkPassphrase: "Test SDF Future Network ; October 2022"; @@ -12,25 +12,13 @@ export declare const networks: { }; }; /** - This is from the rust doc above the struct Test - */ + * This is from the rust doc above the struct Test + */ export interface Test { - /** - - */ a: u32; - /** - - */ b: boolean; - /** - - */ c: string; } -/** - - */ export type SimpleEnum = { tag: "First"; values: void; @@ -41,21 +29,12 @@ export type SimpleEnum = { tag: "Third"; values: void; }; -/** - - */ export declare enum RoyalCard { Jack = 11, Queen = 12, King = 13 } -/** - - */ export type TupleStruct = readonly [Test, SimpleEnum]; -/** - - */ export type ComplexEnum = { tag: "Struct"; values: readonly [Test]; @@ -72,353 +51,576 @@ export type ComplexEnum = { tag: "Void"; values: void; }; -/** - - */ export declare const Errors: { 1: { message: string; }; }; -export declare class Contract { - readonly options: ClassOptions; - spec: ContractSpec; - constructor(options: ClassOptions); - private readonly parsers; - private txFromJSON; - readonly fromJSON: { - hello: (json: string) => AssembledTransaction; - woid: (json: string) => AssembledTransaction; - val: (json: string) => AssembledTransaction; - u32FailOnEven: (json: string) => AssembledTransaction | Ok>; - u32: (json: string) => AssembledTransaction; - i32: (json: string) => AssembledTransaction; - i64: (json: string) => AssembledTransaction; - struktHel: (json: string) => AssembledTransaction; - strukt: (json: string) => AssembledTransaction; - simple: (json: string) => AssembledTransaction; - complex: (json: string) => AssembledTransaction; - addresse: (json: string) => AssembledTransaction; - bytes: (json: string) => AssembledTransaction; - bytesN: (json: string) => AssembledTransaction; - card: (json: string) => AssembledTransaction; - boolean: (json: string) => AssembledTransaction; - not: (json: string) => AssembledTransaction; - i128: (json: string) => AssembledTransaction; - u128: (json: string) => AssembledTransaction; - multiArgs: (json: string) => AssembledTransaction; - map: (json: string) => AssembledTransaction>; - vec: (json: string) => AssembledTransaction; - tuple: (json: string) => AssembledTransaction; - option: (json: string) => AssembledTransaction>; - u256: (json: string) => AssembledTransaction; - i256: (json: string) => AssembledTransaction; - string: (json: string) => AssembledTransaction; - tupleStrukt: (json: string) => AssembledTransaction; - }; +export interface Client { /** -* Construct and simulate a hello transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a hello transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ hello: ({ hello }: { hello: string; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a woid transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a woid transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ woid: (options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a val transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a val transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ val: (options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a u32_fail_on_even transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a u32_fail_on_even transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ u32FailOnEven: ({ u32_ }: { u32_: u32; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise | Ok>>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>>; /** -* Construct and simulate a u32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a u32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ u32: ({ u32_ }: { u32_: u32; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a i32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a i32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ i32: ({ i32_ }: { i32_: i32; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a i64_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a i64_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ i64: ({ i64_ }: { i64_: i64; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a strukt_hel transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Example contract method which takes a struct -*/ + * Construct and simulate a strukt_hel transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. * + * Example contract method which takes a struct + */ struktHel: ({ strukt }: { strukt: Test; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>>; /** -* Construct and simulate a strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ strukt: ({ strukt }: { strukt: Test; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a simple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a simple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ simple: ({ simple }: { simple: SimpleEnum; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a complex transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a complex transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ complex: ({ complex }: { complex: ComplexEnum; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a addresse transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a addresse transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ addresse: ({ addresse }: { addresse: string; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a bytes transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a bytes transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ bytes: ({ bytes }: { bytes: Buffer; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a bytes_n transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a bytes_n transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ bytesN: ({ bytes_n }: { bytes_n: Buffer; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a card transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a card transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ card: ({ card }: { card: RoyalCard; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a boolean transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a boolean transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ boolean: ({ boolean }: { boolean: boolean; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a not transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Negates a boolean value -*/ + * Construct and simulate a not transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. * + * Negates a boolean value + */ not: ({ boolean }: { boolean: boolean; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a i128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a i128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ i128: ({ i128 }: { - i128: bigint; + i128: i128; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a u128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a u128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ u128: ({ u128 }: { - u128: bigint; + u128: u128; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a multi_args transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a multi_args transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ multiArgs: ({ a, b }: { a: u32; b: boolean; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a map transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a map transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ map: ({ map }: { map: Map; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>>; /** -* Construct and simulate a vec transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a vec transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ vec: ({ vec }: { vec: Array; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>>; /** -* Construct and simulate a tuple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a tuple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ tuple: ({ tuple }: { tuple: readonly [string, u32]; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a option transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Example of an optional argument -*/ + * Construct and simulate a option transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. * + * Example of an optional argument + */ option: ({ option }: { option: Option; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>>; /** -* Construct and simulate a u256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a u256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ u256: ({ u256 }: { - u256: bigint; + u256: u256; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a i256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a i256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ i256: ({ i256 }: { - i256: bigint; + i256: i256; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a string transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a string transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ string: ({ string }: { string: string; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a tuple_strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a tuple_strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ tupleStrukt: ({ tuple_strukt }: { tuple_strukt: TupleStruct; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; } +export declare class Client extends ContractClient { + readonly options: ContractClientOptions; + constructor(options: ContractClientOptions); + readonly fromJSON: { + hello: (json: string) => AssembledTransaction; + woid: (json: string) => AssembledTransaction; + val: (json: string) => AssembledTransaction; + u32FailOnEven: (json: string) => AssembledTransaction>; + u32: (json: string) => AssembledTransaction; + i32: (json: string) => AssembledTransaction; + i64: (json: string) => AssembledTransaction; + struktHel: (json: string) => AssembledTransaction; + strukt: (json: string) => AssembledTransaction; + simple: (json: string) => AssembledTransaction; + complex: (json: string) => AssembledTransaction; + addresse: (json: string) => AssembledTransaction; + bytes: (json: string) => AssembledTransaction; + bytesN: (json: string) => AssembledTransaction; + card: (json: string) => AssembledTransaction; + boolean: (json: string) => AssembledTransaction; + not: (json: string) => AssembledTransaction; + i128: (json: string) => AssembledTransaction; + u128: (json: string) => AssembledTransaction; + multiArgs: (json: string) => AssembledTransaction; + map: (json: string) => AssembledTransaction>; + vec: (json: string) => AssembledTransaction; + tuple: (json: string) => AssembledTransaction; + option: (json: string) => AssembledTransaction>; + u256: (json: string) => AssembledTransaction; + i256: (json: string) => AssembledTransaction; + string: (json: string) => AssembledTransaction; + tupleStrukt: (json: string) => AssembledTransaction; + }; +} diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/index.js b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/index.js index d6e27aa855..18ae74e3f5 100644 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/index.js +++ b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/index.js @@ -14,12 +14,13 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.Contract = exports.Errors = exports.RoyalCard = exports.networks = void 0; +exports.Client = exports.Errors = exports.RoyalCard = exports.networks = void 0; const stellar_sdk_1 = require("@stellar/stellar-sdk"); const buffer_1 = require("buffer"); -const assembled_tx_js_1 = require("./assembled-tx.js"); -__exportStar(require("./assembled-tx.js"), exports); -__exportStar(require("./method-options.js"), exports); +const index_js_1 = require("@stellar/stellar-sdk/lib/contract_client/index.js"); +__exportStar(require("@stellar/stellar-sdk"), exports); +__exportStar(require("@stellar/stellar-sdk/lib/contract_client/index.js"), exports); +__exportStar(require("@stellar/stellar-sdk/lib/rust_types/index.js"), exports); if (typeof window !== 'undefined') { //@ts-ignore Buffer exists window.Buffer = window.Buffer || buffer_1.Buffer; @@ -30,28 +31,19 @@ exports.networks = { contractId: "CBYMYMSDF6FBDNCFJCRC7KMO4REYFPOH2U4N7FXI3GJO6YXNCQ43CDSK", } }; -/** - - */ var RoyalCard; (function (RoyalCard) { RoyalCard[RoyalCard["Jack"] = 11] = "Jack"; RoyalCard[RoyalCard["Queen"] = 12] = "Queen"; RoyalCard[RoyalCard["King"] = 13] = "King"; })(RoyalCard || (exports.RoyalCard = RoyalCard = {})); -/** - - */ exports.Errors = { 1: { message: "Please provide an odd number" } }; -class Contract { +class Client extends index_js_1.ContractClient { options; - spec; constructor(options) { - this.options = options; - this.spec = new stellar_sdk_1.ContractSpec([ - "AAAAAQAAAC9UaGlzIGlzIGZyb20gdGhlIHJ1c3QgZG9jIGFib3ZlIHRoZSBzdHJ1Y3QgVGVzdAAAAAAAAAAABFRlc3QAAAADAAAAAAAAAAFhAAAAAAAABAAAAAAAAAABYgAAAAAAAAEAAAAAAAAAAWMAAAAAAAAR", + super(new stellar_sdk_1.ContractSpec(["AAAAAQAAAC9UaGlzIGlzIGZyb20gdGhlIHJ1c3QgZG9jIGFib3ZlIHRoZSBzdHJ1Y3QgVGVzdAAAAAAAAAAABFRlc3QAAAADAAAAAAAAAAFhAAAAAAAABAAAAAAAAAABYgAAAAAAAAEAAAAAAAAAAWMAAAAAAAAR", "AAAAAgAAAAAAAAAAAAAAClNpbXBsZUVudW0AAAAAAAMAAAAAAAAAAAAAAAVGaXJzdAAAAAAAAAAAAAAAAAAABlNlY29uZAAAAAAAAAAAAAAAAAAFVGhpcmQAAAA=", "AAAAAwAAAAAAAAAAAAAACVJveWFsQ2FyZAAAAAAAAAMAAAAAAAAABEphY2sAAAALAAAAAAAAAAVRdWVlbgAAAAAAAAwAAAAAAAAABEtpbmcAAAAN", "AAAAAQAAAAAAAAAAAAAAC1R1cGxlU3RydWN0AAAAAAIAAAAAAAAAATAAAAAAAAfQAAAABFRlc3QAAAAAAAAAATEAAAAAAAfQAAAAClNpbXBsZUVudW0AAA==", @@ -84,51 +76,9 @@ class Contract { "AAAAAAAAAAAAAAAEdTI1NgAAAAEAAAAAAAAABHUyNTYAAAAMAAAAAQAAAAw=", "AAAAAAAAAAAAAAAEaTI1NgAAAAEAAAAAAAAABGkyNTYAAAANAAAAAQAAAA0=", "AAAAAAAAAAAAAAAGc3RyaW5nAAAAAAABAAAAAAAAAAZzdHJpbmcAAAAAABAAAAABAAAAEA==", - "AAAAAAAAAAAAAAAMdHVwbGVfc3RydWt0AAAAAQAAAAAAAAAMdHVwbGVfc3RydWt0AAAH0AAAAAtUdXBsZVN0cnVjdAAAAAABAAAH0AAAAAtUdXBsZVN0cnVjdAA=" - ]); + "AAAAAAAAAAAAAAAMdHVwbGVfc3RydWt0AAAAAQAAAAAAAAAMdHVwbGVfc3RydWt0AAAH0AAAAAtUdXBsZVN0cnVjdAAAAAABAAAH0AAAAAtUdXBsZVN0cnVjdAA="]), options); + this.options = options; } - parsers = { - hello: (result) => this.spec.funcResToNative("hello", result), - woid: () => { }, - val: (result) => this.spec.funcResToNative("val", result), - u32FailOnEven: (result) => { - if (result instanceof assembled_tx_js_1.Err) - return result; - return new assembled_tx_js_1.Ok(this.spec.funcResToNative("u32_fail_on_even", result)); - }, - u32: (result) => this.spec.funcResToNative("u32_", result), - i32: (result) => this.spec.funcResToNative("i32_", result), - i64: (result) => this.spec.funcResToNative("i64_", result), - struktHel: (result) => this.spec.funcResToNative("strukt_hel", result), - strukt: (result) => this.spec.funcResToNative("strukt", result), - simple: (result) => this.spec.funcResToNative("simple", result), - complex: (result) => this.spec.funcResToNative("complex", result), - addresse: (result) => this.spec.funcResToNative("addresse", result), - bytes: (result) => this.spec.funcResToNative("bytes", result), - bytesN: (result) => this.spec.funcResToNative("bytes_n", result), - card: (result) => this.spec.funcResToNative("card", result), - boolean: (result) => this.spec.funcResToNative("boolean", result), - not: (result) => this.spec.funcResToNative("not", result), - i128: (result) => this.spec.funcResToNative("i128", result), - u128: (result) => this.spec.funcResToNative("u128", result), - multiArgs: (result) => this.spec.funcResToNative("multi_args", result), - map: (result) => this.spec.funcResToNative("map", result), - vec: (result) => this.spec.funcResToNative("vec", result), - tuple: (result) => this.spec.funcResToNative("tuple", result), - option: (result) => this.spec.funcResToNative("option", result), - u256: (result) => this.spec.funcResToNative("u256", result), - i256: (result) => this.spec.funcResToNative("i256", result), - string: (result) => this.spec.funcResToNative("string", result), - tupleStrukt: (result) => this.spec.funcResToNative("tuple_strukt", result) - }; - txFromJSON = (json) => { - const { method, ...tx } = JSON.parse(json); - return assembled_tx_js_1.AssembledTransaction.fromJSON({ - ...this.options, - method, - parseResultXdr: this.parsers[method], - }, tx); - }; fromJSON = { hello: (this.txFromJSON), woid: (this.txFromJSON), @@ -159,369 +109,5 @@ class Contract { string: (this.txFromJSON), tupleStrukt: (this.txFromJSON) }; - /** -* Construct and simulate a hello transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - hello = async ({ hello }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'hello', - args: this.spec.funcArgsToScVals("hello", { hello }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['hello'], - }); - }; - /** -* Construct and simulate a woid transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - woid = async (options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'woid', - args: this.spec.funcArgsToScVals("woid", {}), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['woid'], - }); - }; - /** -* Construct and simulate a val transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - val = async (options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'val', - args: this.spec.funcArgsToScVals("val", {}), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['val'], - }); - }; - /** -* Construct and simulate a u32_fail_on_even transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - u32FailOnEven = async ({ u32_ }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'u32_fail_on_even', - args: this.spec.funcArgsToScVals("u32_fail_on_even", { u32_ }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['u32FailOnEven'], - }); - }; - /** -* Construct and simulate a u32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - u32 = async ({ u32_ }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'u32_', - args: this.spec.funcArgsToScVals("u32_", { u32_ }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['u32'], - }); - }; - /** -* Construct and simulate a i32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - i32 = async ({ i32_ }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'i32_', - args: this.spec.funcArgsToScVals("i32_", { i32_ }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['i32'], - }); - }; - /** -* Construct and simulate a i64_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - i64 = async ({ i64_ }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'i64_', - args: this.spec.funcArgsToScVals("i64_", { i64_ }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['i64'], - }); - }; - /** -* Construct and simulate a strukt_hel transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Example contract method which takes a struct -*/ - struktHel = async ({ strukt }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'strukt_hel', - args: this.spec.funcArgsToScVals("strukt_hel", { strukt }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['struktHel'], - }); - }; - /** -* Construct and simulate a strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - strukt = async ({ strukt }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'strukt', - args: this.spec.funcArgsToScVals("strukt", { strukt }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['strukt'], - }); - }; - /** -* Construct and simulate a simple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - simple = async ({ simple }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'simple', - args: this.spec.funcArgsToScVals("simple", { simple }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['simple'], - }); - }; - /** -* Construct and simulate a complex transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - complex = async ({ complex }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'complex', - args: this.spec.funcArgsToScVals("complex", { complex }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['complex'], - }); - }; - /** -* Construct and simulate a addresse transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - addresse = async ({ addresse }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'addresse', - args: this.spec.funcArgsToScVals("addresse", { addresse: new stellar_sdk_1.Address(addresse) }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['addresse'], - }); - }; - /** -* Construct and simulate a bytes transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - bytes = async ({ bytes }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'bytes', - args: this.spec.funcArgsToScVals("bytes", { bytes }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['bytes'], - }); - }; - /** -* Construct and simulate a bytes_n transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - bytesN = async ({ bytes_n }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'bytes_n', - args: this.spec.funcArgsToScVals("bytes_n", { bytes_n }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['bytesN'], - }); - }; - /** -* Construct and simulate a card transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - card = async ({ card }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'card', - args: this.spec.funcArgsToScVals("card", { card }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['card'], - }); - }; - /** -* Construct and simulate a boolean transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - boolean = async ({ boolean }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'boolean', - args: this.spec.funcArgsToScVals("boolean", { boolean }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['boolean'], - }); - }; - /** -* Construct and simulate a not transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Negates a boolean value -*/ - not = async ({ boolean }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'not', - args: this.spec.funcArgsToScVals("not", { boolean }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['not'], - }); - }; - /** -* Construct and simulate a i128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - i128 = async ({ i128 }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'i128', - args: this.spec.funcArgsToScVals("i128", { i128 }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['i128'], - }); - }; - /** -* Construct and simulate a u128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - u128 = async ({ u128 }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'u128', - args: this.spec.funcArgsToScVals("u128", { u128 }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['u128'], - }); - }; - /** -* Construct and simulate a multi_args transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - multiArgs = async ({ a, b }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'multi_args', - args: this.spec.funcArgsToScVals("multi_args", { a, b }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['multiArgs'], - }); - }; - /** -* Construct and simulate a map transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - map = async ({ map }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'map', - args: this.spec.funcArgsToScVals("map", { map }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['map'], - }); - }; - /** -* Construct and simulate a vec transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - vec = async ({ vec }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'vec', - args: this.spec.funcArgsToScVals("vec", { vec }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['vec'], - }); - }; - /** -* Construct and simulate a tuple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - tuple = async ({ tuple }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'tuple', - args: this.spec.funcArgsToScVals("tuple", { tuple }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['tuple'], - }); - }; - /** -* Construct and simulate a option transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Example of an optional argument -*/ - option = async ({ option }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'option', - args: this.spec.funcArgsToScVals("option", { option }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['option'], - }); - }; - /** -* Construct and simulate a u256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - u256 = async ({ u256 }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'u256', - args: this.spec.funcArgsToScVals("u256", { u256 }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['u256'], - }); - }; - /** -* Construct and simulate a i256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - i256 = async ({ i256 }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'i256', - args: this.spec.funcArgsToScVals("i256", { i256 }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['i256'], - }); - }; - /** -* Construct and simulate a string transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - string = async ({ string }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'string', - args: this.spec.funcArgsToScVals("string", { string }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['string'], - }); - }; - /** -* Construct and simulate a tuple_strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - tupleStrukt = async ({ tuple_strukt }, options = {}) => { - return await assembled_tx_js_1.AssembledTransaction.fromSimulation({ - method: 'tuple_strukt', - args: this.spec.funcArgsToScVals("tuple_strukt", { tuple_strukt }), - ...options, - ...this.options, - errorTypes: exports.Errors, - parseResultXdr: this.parsers['tupleStrukt'], - }); - }; } -exports.Contract = Contract; +exports.Client = Client; diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/method-options.d.ts b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/method-options.d.ts deleted file mode 100644 index fc6b21d5d8..0000000000 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/method-options.d.ts +++ /dev/null @@ -1,47 +0,0 @@ -declare let responseTypes: 'simulated' | 'full' | undefined; -export type ResponseTypes = typeof responseTypes; -export type XDR_BASE64 = string; -export interface Wallet { - isConnected: () => Promise; - isAllowed: () => Promise; - getUserInfo: () => Promise<{ - publicKey?: string; - }>; - signTransaction: (tx: XDR_BASE64, opts?: { - network?: string; - networkPassphrase?: string; - accountToSign?: string; - }) => Promise; - signAuthEntry: (entryXdr: XDR_BASE64, opts?: { - accountToSign?: string; - }) => Promise; -} -export type ClassOptions = { - contractId: string; - networkPassphrase: string; - rpcUrl: string; - errorTypes?: Record; - /** - * A Wallet interface, such as Freighter, that has the methods `isConnected`, `isAllowed`, `getUserInfo`, and `signTransaction`. If not provided, will attempt to import and use Freighter. Example: - * - * @example - * ```ts - * import freighter from "@stellar/freighter-api"; - * import { Contract } from "test_custom_types"; - * const contract = new Contract({ - * …, - * wallet: freighter, - * }) - * ``` - */ - wallet?: Wallet; -}; -export type MethodOptions = { - /** - * The fee to pay for the transaction. Default: soroban-sdk's BASE_FEE ('100') - */ - fee?: number; -}; -export {}; diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/method-options.js b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/method-options.js deleted file mode 100644 index 6d483ac325..0000000000 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/cjs/method-options.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -// defined this way so typeahead shows full union, not named alias -let responseTypes; diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/assembled-tx.d.ts b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/assembled-tx.d.ts deleted file mode 100644 index 1d5e6f5ee8..0000000000 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/assembled-tx.d.ts +++ /dev/null @@ -1,184 +0,0 @@ -import { Account, Address, Operation, SorobanRpc, xdr } from "@stellar/stellar-sdk"; -import type { Memo, MemoType, Transaction } from "@stellar/stellar-sdk"; -import type { ClassOptions, MethodOptions, Wallet, XDR_BASE64 } from "./method-options.js"; -export type Tx = Transaction, Operation[]>; -export declare class ExpiredStateError extends Error { -} -export declare class NeedsMoreSignaturesError extends Error { -} -export declare class WalletDisconnectedError extends Error { -} -export declare class SendResultOnlyError extends Error { -} -export declare class SendFailedError extends Error { -} -export declare class NoUnsignedNonInvokerAuthEntriesError extends Error { -} -type SendTx = SorobanRpc.Api.SendTransactionResponse; -type GetTx = SorobanRpc.Api.GetTransactionResponse; -export type u32 = number; -export type i32 = number; -export type u64 = bigint; -export type i64 = bigint; -export type u128 = bigint; -export type i128 = bigint; -export type u256 = bigint; -export type i256 = bigint; -export type Option = T | undefined; -export type Typepoint = bigint; -export type Duration = bigint; -export { Address }; -export interface Error_ { - message: string; -} -export interface Result { - unwrap(): T; - unwrapErr(): E; - isOk(): boolean; - isErr(): boolean; -} -export declare class Ok implements Result { - readonly value: T; - constructor(value: T); - unwrapErr(): E; - unwrap(): T; - isOk(): boolean; - isErr(): boolean; -} -export declare class Err implements Result { - readonly error: E; - constructor(error: E); - unwrapErr(): E; - unwrap(): never; - isOk(): boolean; - isErr(): boolean; -} -export declare const contractErrorPattern: RegExp; -type AssembledTransactionOptions = MethodOptions & ClassOptions & { - method: string; - args?: any[]; - parseResultXdr: (xdr: string | xdr.ScVal | Err) => T; -}; -export declare const NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; -export declare class AssembledTransaction { - options: AssembledTransactionOptions; - raw: Tx; - private simulation?; - private simulationResult?; - private simulationTransactionData?; - private server; - toJSON(): string; - static fromJSON(options: Omit, 'args'>, { tx, simulationResult, simulationTransactionData }: { - tx: XDR_BASE64; - simulationResult: { - auth: XDR_BASE64[]; - retval: XDR_BASE64; - }; - simulationTransactionData: XDR_BASE64; - }): AssembledTransaction; - private constructor(); - static fromSimulation(options: AssembledTransactionOptions): Promise>; - simulate: () => Promise; - get simulationData(): { - result: SorobanRpc.Api.SimulateHostFunctionResult; - transactionData: xdr.SorobanTransactionData; - }; - get result(): T; - parseError(errorMessage: string): Err | undefined; - getWallet: () => Promise; - getPublicKey: () => Promise; - /** - * Get account details from the Soroban network for the publicKey currently - * selected in user's wallet. If not connected to Freighter, use placeholder - * null account. - */ - getAccount: () => Promise; - /** - * Sign the transaction with the `wallet` (default Freighter), then send to - * the network and return a `SentTransaction` that keeps track of all the - * attempts to send and fetch the transaction from the network. - */ - signAndSend: ({ secondsToWait, force }?: { - /** - * Wait `secondsToWait` seconds (default: 10) for both the transaction to SEND successfully (will keep trying if the server returns `TRY_AGAIN_LATER`), as well as for the transaction to COMPLETE (will keep checking if the server returns `PENDING`). - */ - secondsToWait?: number | undefined; - /** - * If `true`, sign and send the transaction even if it is a read call. - */ - force?: boolean | undefined; - }) => Promise>; - getStorageExpiration: () => Promise; - /** - * Get a list of accounts, other than the invoker of the simulation, that - * need to sign auth entries in this transaction. - * - * Soroban allows multiple people to sign a transaction. Someone needs to - * sign the final transaction envelope; this person/account is called the - * _invoker_, or _source_. Other accounts might need to sign individual auth - * entries in the transaction, if they're not also the invoker. - * - * This function returns a list of accounts that need to sign auth entries, - * assuming that the same invoker/source account will sign the final - * transaction envelope as signed the initial simulation. - * - * One at a time, for each public key in this array, you will need to - * serialize this transaction with `toJSON`, send to the owner of that key, - * deserialize the transaction with `txFromJson`, and call - * {@link signAuthEntries}. Then re-serialize and send to the next account - * in this list. - */ - needsNonInvokerSigningBy: ({ includeAlreadySigned, }?: { - /** - * Whether or not to include auth entries that have already been signed. Default: false - */ - includeAlreadySigned?: boolean | undefined; - }) => Promise; - preImageFor(entry: xdr.SorobanAuthorizationEntry, signatureExpirationLedger: number): xdr.HashIdPreimage; - /** - * If {@link needsNonInvokerSigningBy} returns a non-empty list, you can serialize - * the transaction with `toJSON`, send it to the owner of one of the public keys - * in the map, deserialize with `txFromJSON`, and call this method on their - * machine. Internally, this will use `signAuthEntry` function from connected - * `wallet` for each. - * - * Then, re-serialize the transaction and either send to the next - * `needsNonInvokerSigningBy` owner, or send it back to the original account - * who simulated the transaction so they can {@link sign} the transaction - * envelope and {@link send} it to the network. - * - * Sending to all `needsNonInvokerSigningBy` owners in parallel is not currently - * supported! - */ - signAuthEntries: (expiration?: number | Promise) => Promise; - get isReadCall(): boolean; - hasRealInvoker: () => Promise; -} -/** - * A transaction that has been sent to the Soroban network. This happens in two steps: - * - * 1. `sendTransaction`: initial submission of the transaction to the network. - * This step can run into problems, and will be retried with exponential - * backoff if it does. See all attempts in `sendTransactionResponseAll` and the - * most recent attempt in `sendTransactionResponse`. - * 2. `getTransaction`: once the transaction has been submitted to the network - * successfully, you need to wait for it to finalize to get the results of the - * transaction. This step can also run into problems, and will be retried with - * exponential backoff if it does. See all attempts in - * `getTransactionResponseAll` and the most recent attempt in - * `getTransactionResponse`. - */ -declare class SentTransaction { - options: AssembledTransactionOptions; - assembled: AssembledTransaction; - server: SorobanRpc.Server; - signed: Tx; - sendTransactionResponse?: SendTx; - sendTransactionResponseAll?: SendTx[]; - getTransactionResponse?: GetTx; - getTransactionResponseAll?: GetTx[]; - constructor(options: AssembledTransactionOptions, assembled: AssembledTransaction); - static init: (options: AssembledTransactionOptions, assembled: AssembledTransaction, secondsToWait?: number) => Promise>; - private send; - get result(): T; -} diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/assembled-tx.js b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/assembled-tx.js deleted file mode 100644 index 79b7c01d95..0000000000 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/assembled-tx.js +++ /dev/null @@ -1,450 +0,0 @@ -import { Account, Address, Contract, Operation, SorobanRpc, StrKey, TimeoutInfinite, TransactionBuilder, authorizeEntry, hash, xdr, BASE_FEE, } from "@stellar/stellar-sdk"; -import { Buffer } from "buffer"; -export class ExpiredStateError extends Error { -} -export class NeedsMoreSignaturesError extends Error { -} -export class WalletDisconnectedError extends Error { -} -export class SendResultOnlyError extends Error { -} -export class SendFailedError extends Error { -} -export class NoUnsignedNonInvokerAuthEntriesError extends Error { -} -export { Address }; -; -; -export class Ok { - value; - constructor(value) { - this.value = value; - } - unwrapErr() { - throw new Error('No error'); - } - unwrap() { - return this.value; - } - isOk() { - return true; - } - isErr() { - return !this.isOk(); - } -} -export class Err { - error; - constructor(error) { - this.error = error; - } - unwrapErr() { - return this.error; - } - unwrap() { - throw new Error(this.error.message); - } - isOk() { - return false; - } - isErr() { - return !this.isOk(); - } -} -export const contractErrorPattern = /Error\(Contract, #(\d+)\)/; -export const NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; -export class AssembledTransaction { - options; - raw; - simulation; - simulationResult; - simulationTransactionData; - server; - toJSON() { - return JSON.stringify({ - method: this.options.method, - tx: this.raw?.toXDR(), - simulationResult: { - auth: this.simulationData.result.auth.map(a => a.toXDR('base64')), - retval: this.simulationData.result.retval.toXDR('base64'), - }, - simulationTransactionData: this.simulationData.transactionData.toXDR('base64'), - }); - } - static fromJSON(options, { tx, simulationResult, simulationTransactionData }) { - const txn = new AssembledTransaction(options); - txn.raw = TransactionBuilder.fromXDR(tx, options.networkPassphrase); - txn.simulationResult = { - auth: simulationResult.auth.map(a => xdr.SorobanAuthorizationEntry.fromXDR(a, 'base64')), - retval: xdr.ScVal.fromXDR(simulationResult.retval, 'base64'), - }; - txn.simulationTransactionData = xdr.SorobanTransactionData.fromXDR(simulationTransactionData, 'base64'); - return txn; - } - constructor(options) { - this.options = options; - this.server = new SorobanRpc.Server(this.options.rpcUrl, { - allowHttp: this.options.rpcUrl.startsWith("http://"), - }); - } - static async fromSimulation(options) { - const tx = new AssembledTransaction(options); - const contract = new Contract(options.contractId); - tx.raw = new TransactionBuilder(await tx.getAccount(), { - fee: options.fee?.toString(10) ?? BASE_FEE, - networkPassphrase: options.networkPassphrase, - }) - .addOperation(contract.call(options.method, ...(options.args ?? []))) - .setTimeout(TimeoutInfinite) - .build(); - return await tx.simulate(); - } - simulate = async () => { - if (!this.raw) - throw new Error('Transaction has not yet been assembled'); - this.simulation = await this.server.simulateTransaction(this.raw); - if (SorobanRpc.Api.isSimulationSuccess(this.simulation)) { - this.raw = SorobanRpc.assembleTransaction(this.raw, this.simulation).build(); - } - return this; - }; - get simulationData() { - if (this.simulationResult && this.simulationTransactionData) { - return { - result: this.simulationResult, - transactionData: this.simulationTransactionData, - }; - } - // else, we know we just did the simulation on this machine - const simulation = this.simulation; - if (SorobanRpc.Api.isSimulationError(simulation)) { - throw new Error(`Transaction simulation failed: "${simulation.error}"`); - } - if (SorobanRpc.Api.isSimulationRestore(simulation)) { - throw new ExpiredStateError(`You need to restore some contract state before you can invoke this method. ${JSON.stringify(simulation, null, 2)}`); - } - if (!simulation.result) { - throw new Error(`Expected an invocation simulation, but got no 'result' field. Simulation: ${JSON.stringify(simulation, null, 2)}`); - } - // add to object for serialization & deserialization - this.simulationResult = simulation.result; - this.simulationTransactionData = simulation.transactionData.build(); - return { - result: this.simulationResult, - transactionData: this.simulationTransactionData, - }; - } - get result() { - try { - return this.options.parseResultXdr(this.simulationData.result.retval); - } - catch (e) { - let err = this.parseError(e.toString()); - if (err) - return err; - throw e; - } - } - parseError(errorMessage) { - if (!this.options.errorTypes) - return; - const match = errorMessage.match(contractErrorPattern); - if (!match) - return; - let i = parseInt(match[1], 10); - let err = this.options.errorTypes[i]; - if (err) - return new Err(err); - } - getWallet = async () => { - return this.options.wallet ?? (await import("@stellar/freighter-api")).default; - }; - getPublicKey = async () => { - const wallet = await this.getWallet(); - if (await wallet.isConnected() && await wallet.isAllowed()) { - return (await wallet.getUserInfo()).publicKey; - } - }; - /** - * Get account details from the Soroban network for the publicKey currently - * selected in user's wallet. If not connected to Freighter, use placeholder - * null account. - */ - getAccount = async () => { - const publicKey = await this.getPublicKey(); - return publicKey - ? await this.server.getAccount(publicKey) - : new Account(NULL_ACCOUNT, "0"); - }; - /** - * Sign the transaction with the `wallet` (default Freighter), then send to - * the network and return a `SentTransaction` that keeps track of all the - * attempts to send and fetch the transaction from the network. - */ - signAndSend = async ({ secondsToWait = 10, force = false } = {}) => { - if (!this.raw) { - throw new Error('Transaction has not yet been simulated'); - } - if (!force && this.isReadCall) { - throw new Error('This is a read call. It requires no signature or sending. Use `force: true` to sign and send anyway.'); - } - if (!await this.hasRealInvoker()) { - throw new WalletDisconnectedError('Wallet is not connected'); - } - if (this.raw.source !== (await this.getAccount()).accountId()) { - throw new Error(`You must submit the transaction with the account that originally created it. Please switch to the wallet with "${this.raw.source}" as its public key.`); - } - if ((await this.needsNonInvokerSigningBy()).length) { - throw new NeedsMoreSignaturesError('Transaction requires more signatures. See `needsNonInvokerSigningBy` for details.'); - } - return await SentTransaction.init(this.options, this, secondsToWait); - }; - getStorageExpiration = async () => { - const entryRes = await this.server.getLedgerEntries(new Contract(this.options.contractId).getFootprint()); - if (!entryRes.entries || - !entryRes.entries.length || - !entryRes.entries[0].liveUntilLedgerSeq) - throw new Error('failed to get ledger entry'); - return entryRes.entries[0].liveUntilLedgerSeq; - }; - /** - * Get a list of accounts, other than the invoker of the simulation, that - * need to sign auth entries in this transaction. - * - * Soroban allows multiple people to sign a transaction. Someone needs to - * sign the final transaction envelope; this person/account is called the - * _invoker_, or _source_. Other accounts might need to sign individual auth - * entries in the transaction, if they're not also the invoker. - * - * This function returns a list of accounts that need to sign auth entries, - * assuming that the same invoker/source account will sign the final - * transaction envelope as signed the initial simulation. - * - * One at a time, for each public key in this array, you will need to - * serialize this transaction with `toJSON`, send to the owner of that key, - * deserialize the transaction with `txFromJson`, and call - * {@link signAuthEntries}. Then re-serialize and send to the next account - * in this list. - */ - needsNonInvokerSigningBy = async ({ includeAlreadySigned = false, } = {}) => { - if (!this.raw) { - throw new Error('Transaction has not yet been simulated'); - } - // We expect that any transaction constructed by these libraries has a - // single operation, which is an InvokeHostFunction operation. The host - // function being invoked is the contract method call. - if (!("operations" in this.raw)) { - throw new Error(`Unexpected Transaction type; no operations: ${JSON.stringify(this.raw)}`); - } - const rawInvokeHostFunctionOp = this.raw - .operations[0]; - return [...new Set((rawInvokeHostFunctionOp.auth ?? []).filter(entry => entry.credentials().switch() === - xdr.SorobanCredentialsType.sorobanCredentialsAddress() && - (includeAlreadySigned || - entry.credentials().address().signature().switch().name === 'scvVoid')).map(entry => StrKey.encodeEd25519PublicKey(entry.credentials().address().address().accountId().ed25519())))]; - }; - preImageFor(entry, signatureExpirationLedger) { - const addrAuth = entry.credentials().address(); - return xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(new xdr.HashIdPreimageSorobanAuthorization({ - networkId: hash(Buffer.from(this.options.networkPassphrase)), - nonce: addrAuth.nonce(), - invocation: entry.rootInvocation(), - signatureExpirationLedger, - })); - } - /** - * If {@link needsNonInvokerSigningBy} returns a non-empty list, you can serialize - * the transaction with `toJSON`, send it to the owner of one of the public keys - * in the map, deserialize with `txFromJSON`, and call this method on their - * machine. Internally, this will use `signAuthEntry` function from connected - * `wallet` for each. - * - * Then, re-serialize the transaction and either send to the next - * `needsNonInvokerSigningBy` owner, or send it back to the original account - * who simulated the transaction so they can {@link sign} the transaction - * envelope and {@link send} it to the network. - * - * Sending to all `needsNonInvokerSigningBy` owners in parallel is not currently - * supported! - */ - signAuthEntries = async ( - /** - * When to set each auth entry to expire. Could be any number of blocks in - * the future. Can be supplied as a promise or a raw number. Default: - * contract's current `persistent` storage expiration date/ledger - * number/block. - */ - expiration = this.getStorageExpiration()) => { - if (!this.raw) - throw new Error('Transaction has not yet been assembled or simulated'); - const needsNonInvokerSigningBy = await this.needsNonInvokerSigningBy(); - if (!needsNonInvokerSigningBy) - throw new NoUnsignedNonInvokerAuthEntriesError('No unsigned non-invoker auth entries; maybe you already signed?'); - const publicKey = await this.getPublicKey(); - if (!publicKey) - throw new Error('Could not get public key from wallet; maybe Freighter is not signed in?'); - if (needsNonInvokerSigningBy.indexOf(publicKey) === -1) - throw new Error(`No auth entries for public key "${publicKey}"`); - const wallet = await this.getWallet(); - const rawInvokeHostFunctionOp = this.raw - .operations[0]; - const authEntries = rawInvokeHostFunctionOp.auth ?? []; - for (const [i, entry] of authEntries.entries()) { - if (entry.credentials().switch() !== - xdr.SorobanCredentialsType.sorobanCredentialsAddress()) { - // if the invoker/source account, then the entry doesn't need explicit - // signature, since the tx envelope is already signed by the source - // account, so only check for sorobanCredentialsAddress - continue; - } - const pk = StrKey.encodeEd25519PublicKey(entry.credentials().address().address().accountId().ed25519()); - // this auth entry needs to be signed by a different account - // (or maybe already was!) - if (pk !== publicKey) - continue; - authEntries[i] = await authorizeEntry(entry, async (preimage) => Buffer.from(await wallet.signAuthEntry(preimage.toXDR('base64')), 'base64'), await expiration, this.options.networkPassphrase); - } - }; - get isReadCall() { - const authsCount = this.simulationData.result.auth.length; - const writeLength = this.simulationData.transactionData.resources().footprint().readWrite().length; - return (authsCount === 0) && (writeLength === 0); - } - hasRealInvoker = async () => { - const account = await this.getAccount(); - return account.accountId() !== NULL_ACCOUNT; - }; -} -/** - * A transaction that has been sent to the Soroban network. This happens in two steps: - * - * 1. `sendTransaction`: initial submission of the transaction to the network. - * This step can run into problems, and will be retried with exponential - * backoff if it does. See all attempts in `sendTransactionResponseAll` and the - * most recent attempt in `sendTransactionResponse`. - * 2. `getTransaction`: once the transaction has been submitted to the network - * successfully, you need to wait for it to finalize to get the results of the - * transaction. This step can also run into problems, and will be retried with - * exponential backoff if it does. See all attempts in - * `getTransactionResponseAll` and the most recent attempt in - * `getTransactionResponse`. - */ -class SentTransaction { - options; - assembled; - server; - signed; - sendTransactionResponse; - sendTransactionResponseAll; - getTransactionResponse; - getTransactionResponseAll; - constructor(options, assembled) { - this.options = options; - this.assembled = assembled; - this.server = new SorobanRpc.Server(this.options.rpcUrl, { - allowHttp: this.options.rpcUrl.startsWith("http://"), - }); - this.assembled = assembled; - } - static init = async (options, assembled, secondsToWait = 10) => { - const tx = new SentTransaction(options, assembled); - return await tx.send(secondsToWait); - }; - send = async (secondsToWait = 10) => { - const wallet = await this.assembled.getWallet(); - this.sendTransactionResponseAll = await withExponentialBackoff(async (previousFailure) => { - if (previousFailure) { - // Increment transaction sequence number and resimulate before trying again - // Soroban transaction can only have 1 operation - const op = this.assembled.raw.operations[0]; - this.assembled.raw = new TransactionBuilder(await this.assembled.getAccount(), { - fee: this.assembled.raw.fee, - networkPassphrase: this.options.networkPassphrase, - }) - .setTimeout(TimeoutInfinite) - .addOperation(Operation.invokeHostFunction({ ...op, auth: op.auth ?? [] })) - .build(); - await this.assembled.simulate(); - } - const signature = await wallet.signTransaction(this.assembled.raw.toXDR(), { - networkPassphrase: this.options.networkPassphrase, - }); - this.signed = TransactionBuilder.fromXDR(signature, this.options.networkPassphrase); - return this.server.sendTransaction(this.signed); - }, resp => resp.status !== "PENDING", secondsToWait); - this.sendTransactionResponse = this.sendTransactionResponseAll[this.sendTransactionResponseAll.length - 1]; - if (this.sendTransactionResponse.status !== "PENDING") { - throw new Error(`Tried to resubmit transaction for ${secondsToWait} seconds, but it's still failing. ` + - `All attempts: ${JSON.stringify(this.sendTransactionResponseAll, null, 2)}`); - } - const { hash } = this.sendTransactionResponse; - this.getTransactionResponseAll = await withExponentialBackoff(() => this.server.getTransaction(hash), resp => resp.status === SorobanRpc.Api.GetTransactionStatus.NOT_FOUND, secondsToWait); - this.getTransactionResponse = this.getTransactionResponseAll[this.getTransactionResponseAll.length - 1]; - if (this.getTransactionResponse.status === SorobanRpc.Api.GetTransactionStatus.NOT_FOUND) { - console.error(`Waited ${secondsToWait} seconds for transaction to complete, but it did not. ` + - `Returning anyway. Check the transaction status manually. ` + - `Sent transaction: ${JSON.stringify(this.sendTransactionResponse, null, 2)}\n` + - `All attempts to get the result: ${JSON.stringify(this.getTransactionResponseAll, null, 2)}`); - } - return this; - }; - get result() { - // 1. check if transaction was submitted and awaited with `getTransaction` - if ("getTransactionResponse" in this && - this.getTransactionResponse) { - // getTransactionResponse has a `returnValue` field unless it failed - if ("returnValue" in this.getTransactionResponse) { - return this.options.parseResultXdr(this.getTransactionResponse.returnValue); - } - // if "returnValue" not present, the transaction failed; return without parsing the result - throw new Error("Transaction failed! Cannot parse result."); - } - // 2. otherwise, maybe it was merely sent with `sendTransaction` - if (this.sendTransactionResponse) { - const errorResult = this.sendTransactionResponse.errorResult?.result(); - if (errorResult) { - throw new SendFailedError(`Transaction simulation looked correct, but attempting to send the transaction failed. Check \`simulation\` and \`sendTransactionResponseAll\` to troubleshoot. Decoded \`sendTransactionResponse.errorResultXdr\`: ${errorResult}`); - } - throw new SendResultOnlyError(`Transaction was sent to the network, but not yet awaited. No result to show. Await transaction completion with \`getTransaction(sendTransactionResponse.hash)\``); - } - // 3. finally, if neither of those are present, throw an error - throw new Error(`Sending transaction failed: ${JSON.stringify(this.assembled)}`); - } -} -/** - * Keep calling a `fn` for `secondsToWait` seconds, if `keepWaitingIf` is true. - * Returns an array of all attempts to call the function. - */ -async function withExponentialBackoff(fn, keepWaitingIf, secondsToWait, exponentialFactor = 1.5, verbose = false) { - const attempts = []; - let count = 0; - attempts.push(await fn()); - if (!keepWaitingIf(attempts[attempts.length - 1])) - return attempts; - const waitUntil = new Date(Date.now() + secondsToWait * 1000).valueOf(); - let waitTime = 1000; - let totalWaitTime = waitTime; - while (Date.now() < waitUntil && keepWaitingIf(attempts[attempts.length - 1])) { - count++; - // Wait a beat - if (verbose) { - console.info(`Waiting ${waitTime}ms before trying again (bringing the total wait time to ${totalWaitTime}ms so far, of total ${secondsToWait * 1000}ms)`); - } - await new Promise(res => setTimeout(res, waitTime)); - // Exponential backoff - waitTime = waitTime * exponentialFactor; - if (new Date(Date.now() + waitTime).valueOf() > waitUntil) { - waitTime = waitUntil - Date.now(); - if (verbose) { - console.info(`was gonna wait too long; new waitTime: ${waitTime}ms`); - } - } - totalWaitTime = waitTime + totalWaitTime; - // Try again - attempts.push(await fn(attempts[attempts.length - 1])); - if (verbose && keepWaitingIf(attempts[attempts.length - 1])) { - console.info(`${count}. Called ${fn}; ${attempts.length} prev attempts. Most recent: ${JSON.stringify(attempts[attempts.length - 1], null, 2)}`); - } - } - return attempts; -} diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/index.d.ts b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/index.d.ts index 66d3d59597..58a5712000 100644 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/index.d.ts +++ b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/index.d.ts @@ -1,10 +1,10 @@ -import { ContractSpec } from '@stellar/stellar-sdk'; import { Buffer } from "buffer"; -import { AssembledTransaction, Ok, Err } from './assembled-tx.js'; -import type { u32, i32, i64, i128, Option, Error_ } from './assembled-tx.js'; -import type { ClassOptions } from './method-options.js'; -export * from './assembled-tx.js'; -export * from './method-options.js'; +import { AssembledTransaction, ContractClient, ContractClientOptions } from '@stellar/stellar-sdk/lib/contract_client/index.js'; +import type { u32, i32, i64, u128, i128, u256, i256, Option } from '@stellar/stellar-sdk/lib/contract_client'; +import { Result } from '@stellar/stellar-sdk/lib/rust_types/index.js'; +export * from '@stellar/stellar-sdk'; +export * from '@stellar/stellar-sdk/lib/contract_client/index.js'; +export * from '@stellar/stellar-sdk/lib/rust_types/index.js'; export declare const networks: { readonly futurenet: { readonly networkPassphrase: "Test SDF Future Network ; October 2022"; @@ -12,25 +12,13 @@ export declare const networks: { }; }; /** - This is from the rust doc above the struct Test - */ + * This is from the rust doc above the struct Test + */ export interface Test { - /** - - */ a: u32; - /** - - */ b: boolean; - /** - - */ c: string; } -/** - - */ export type SimpleEnum = { tag: "First"; values: void; @@ -41,21 +29,12 @@ export type SimpleEnum = { tag: "Third"; values: void; }; -/** - - */ export declare enum RoyalCard { Jack = 11, Queen = 12, King = 13 } -/** - - */ export type TupleStruct = readonly [Test, SimpleEnum]; -/** - - */ export type ComplexEnum = { tag: "Struct"; values: readonly [Test]; @@ -72,353 +51,576 @@ export type ComplexEnum = { tag: "Void"; values: void; }; -/** - - */ export declare const Errors: { 1: { message: string; }; }; -export declare class Contract { - readonly options: ClassOptions; - spec: ContractSpec; - constructor(options: ClassOptions); - private readonly parsers; - private txFromJSON; - readonly fromJSON: { - hello: (json: string) => AssembledTransaction; - woid: (json: string) => AssembledTransaction; - val: (json: string) => AssembledTransaction; - u32FailOnEven: (json: string) => AssembledTransaction | Ok>; - u32: (json: string) => AssembledTransaction; - i32: (json: string) => AssembledTransaction; - i64: (json: string) => AssembledTransaction; - struktHel: (json: string) => AssembledTransaction; - strukt: (json: string) => AssembledTransaction; - simple: (json: string) => AssembledTransaction; - complex: (json: string) => AssembledTransaction; - addresse: (json: string) => AssembledTransaction; - bytes: (json: string) => AssembledTransaction; - bytesN: (json: string) => AssembledTransaction; - card: (json: string) => AssembledTransaction; - boolean: (json: string) => AssembledTransaction; - not: (json: string) => AssembledTransaction; - i128: (json: string) => AssembledTransaction; - u128: (json: string) => AssembledTransaction; - multiArgs: (json: string) => AssembledTransaction; - map: (json: string) => AssembledTransaction>; - vec: (json: string) => AssembledTransaction; - tuple: (json: string) => AssembledTransaction; - option: (json: string) => AssembledTransaction>; - u256: (json: string) => AssembledTransaction; - i256: (json: string) => AssembledTransaction; - string: (json: string) => AssembledTransaction; - tupleStrukt: (json: string) => AssembledTransaction; - }; +export interface Client { /** -* Construct and simulate a hello transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a hello transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ hello: ({ hello }: { hello: string; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a woid transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a woid transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ woid: (options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a val transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a val transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ val: (options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a u32_fail_on_even transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a u32_fail_on_even transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ u32FailOnEven: ({ u32_ }: { u32_: u32; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise | Ok>>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>>; /** -* Construct and simulate a u32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a u32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ u32: ({ u32_ }: { u32_: u32; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a i32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a i32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ i32: ({ i32_ }: { i32_: i32; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a i64_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a i64_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ i64: ({ i64_ }: { i64_: i64; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a strukt_hel transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Example contract method which takes a struct -*/ + * Construct and simulate a strukt_hel transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. * + * Example contract method which takes a struct + */ struktHel: ({ strukt }: { strukt: Test; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>>; /** -* Construct and simulate a strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ strukt: ({ strukt }: { strukt: Test; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a simple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a simple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ simple: ({ simple }: { simple: SimpleEnum; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a complex transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a complex transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ complex: ({ complex }: { complex: ComplexEnum; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a addresse transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a addresse transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ addresse: ({ addresse }: { addresse: string; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a bytes transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a bytes transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ bytes: ({ bytes }: { bytes: Buffer; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a bytes_n transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a bytes_n transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ bytesN: ({ bytes_n }: { bytes_n: Buffer; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a card transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a card transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ card: ({ card }: { card: RoyalCard; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a boolean transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a boolean transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ boolean: ({ boolean }: { boolean: boolean; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a not transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Negates a boolean value -*/ + * Construct and simulate a not transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. * + * Negates a boolean value + */ not: ({ boolean }: { boolean: boolean; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a i128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a i128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ i128: ({ i128 }: { - i128: bigint; + i128: i128; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a u128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a u128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ u128: ({ u128 }: { - u128: bigint; + u128: u128; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a multi_args transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a multi_args transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ multiArgs: ({ a, b }: { a: u32; b: boolean; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a map transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a map transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ map: ({ map }: { map: Map; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>>; /** -* Construct and simulate a vec transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a vec transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ vec: ({ vec }: { vec: Array; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>>; /** -* Construct and simulate a tuple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a tuple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ tuple: ({ tuple }: { tuple: readonly [string, u32]; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a option transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Example of an optional argument -*/ + * Construct and simulate a option transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. * + * Example of an optional argument + */ option: ({ option }: { option: Option; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>>; /** -* Construct and simulate a u256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a u256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ u256: ({ u256 }: { - u256: bigint; + u256: u256; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a i256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a i256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ i256: ({ i256 }: { - i256: bigint; + i256: i256; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a string transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a string transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ string: ({ string }: { string: string; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a tuple_strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a tuple_strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ tupleStrukt: ({ tuple_strukt }: { tuple_strukt: TupleStruct; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; } +export declare class Client extends ContractClient { + readonly options: ContractClientOptions; + constructor(options: ContractClientOptions); + readonly fromJSON: { + hello: (json: string) => AssembledTransaction; + woid: (json: string) => AssembledTransaction; + val: (json: string) => AssembledTransaction; + u32FailOnEven: (json: string) => AssembledTransaction>; + u32: (json: string) => AssembledTransaction; + i32: (json: string) => AssembledTransaction; + i64: (json: string) => AssembledTransaction; + struktHel: (json: string) => AssembledTransaction; + strukt: (json: string) => AssembledTransaction; + simple: (json: string) => AssembledTransaction; + complex: (json: string) => AssembledTransaction; + addresse: (json: string) => AssembledTransaction; + bytes: (json: string) => AssembledTransaction; + bytesN: (json: string) => AssembledTransaction; + card: (json: string) => AssembledTransaction; + boolean: (json: string) => AssembledTransaction; + not: (json: string) => AssembledTransaction; + i128: (json: string) => AssembledTransaction; + u128: (json: string) => AssembledTransaction; + multiArgs: (json: string) => AssembledTransaction; + map: (json: string) => AssembledTransaction>; + vec: (json: string) => AssembledTransaction; + tuple: (json: string) => AssembledTransaction; + option: (json: string) => AssembledTransaction>; + u256: (json: string) => AssembledTransaction; + i256: (json: string) => AssembledTransaction; + string: (json: string) => AssembledTransaction; + tupleStrukt: (json: string) => AssembledTransaction; + }; +} diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/index.js b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/index.js index b97cff55c9..df40e6ec43 100644 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/index.js +++ b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/index.js @@ -1,8 +1,9 @@ -import { ContractSpec, Address } from '@stellar/stellar-sdk'; +import { ContractSpec } from '@stellar/stellar-sdk'; import { Buffer } from "buffer"; -import { AssembledTransaction, Ok, Err } from './assembled-tx.js'; -export * from './assembled-tx.js'; -export * from './method-options.js'; +import { ContractClient, } from '@stellar/stellar-sdk/lib/contract_client/index.js'; +export * from '@stellar/stellar-sdk'; +export * from '@stellar/stellar-sdk/lib/contract_client/index.js'; +export * from '@stellar/stellar-sdk/lib/rust_types/index.js'; if (typeof window !== 'undefined') { //@ts-ignore Buffer exists window.Buffer = window.Buffer || Buffer; @@ -13,28 +14,19 @@ export const networks = { contractId: "CBYMYMSDF6FBDNCFJCRC7KMO4REYFPOH2U4N7FXI3GJO6YXNCQ43CDSK", } }; -/** - - */ export var RoyalCard; (function (RoyalCard) { RoyalCard[RoyalCard["Jack"] = 11] = "Jack"; RoyalCard[RoyalCard["Queen"] = 12] = "Queen"; RoyalCard[RoyalCard["King"] = 13] = "King"; })(RoyalCard || (RoyalCard = {})); -/** - - */ export const Errors = { 1: { message: "Please provide an odd number" } }; -export class Contract { +export class Client extends ContractClient { options; - spec; constructor(options) { - this.options = options; - this.spec = new ContractSpec([ - "AAAAAQAAAC9UaGlzIGlzIGZyb20gdGhlIHJ1c3QgZG9jIGFib3ZlIHRoZSBzdHJ1Y3QgVGVzdAAAAAAAAAAABFRlc3QAAAADAAAAAAAAAAFhAAAAAAAABAAAAAAAAAABYgAAAAAAAAEAAAAAAAAAAWMAAAAAAAAR", + super(new ContractSpec(["AAAAAQAAAC9UaGlzIGlzIGZyb20gdGhlIHJ1c3QgZG9jIGFib3ZlIHRoZSBzdHJ1Y3QgVGVzdAAAAAAAAAAABFRlc3QAAAADAAAAAAAAAAFhAAAAAAAABAAAAAAAAAABYgAAAAAAAAEAAAAAAAAAAWMAAAAAAAAR", "AAAAAgAAAAAAAAAAAAAAClNpbXBsZUVudW0AAAAAAAMAAAAAAAAAAAAAAAVGaXJzdAAAAAAAAAAAAAAAAAAABlNlY29uZAAAAAAAAAAAAAAAAAAFVGhpcmQAAAA=", "AAAAAwAAAAAAAAAAAAAACVJveWFsQ2FyZAAAAAAAAAMAAAAAAAAABEphY2sAAAALAAAAAAAAAAVRdWVlbgAAAAAAAAwAAAAAAAAABEtpbmcAAAAN", "AAAAAQAAAAAAAAAAAAAAC1R1cGxlU3RydWN0AAAAAAIAAAAAAAAAATAAAAAAAAfQAAAABFRlc3QAAAAAAAAAATEAAAAAAAfQAAAAClNpbXBsZUVudW0AAA==", @@ -67,51 +59,9 @@ export class Contract { "AAAAAAAAAAAAAAAEdTI1NgAAAAEAAAAAAAAABHUyNTYAAAAMAAAAAQAAAAw=", "AAAAAAAAAAAAAAAEaTI1NgAAAAEAAAAAAAAABGkyNTYAAAANAAAAAQAAAA0=", "AAAAAAAAAAAAAAAGc3RyaW5nAAAAAAABAAAAAAAAAAZzdHJpbmcAAAAAABAAAAABAAAAEA==", - "AAAAAAAAAAAAAAAMdHVwbGVfc3RydWt0AAAAAQAAAAAAAAAMdHVwbGVfc3RydWt0AAAH0AAAAAtUdXBsZVN0cnVjdAAAAAABAAAH0AAAAAtUdXBsZVN0cnVjdAA=" - ]); + "AAAAAAAAAAAAAAAMdHVwbGVfc3RydWt0AAAAAQAAAAAAAAAMdHVwbGVfc3RydWt0AAAH0AAAAAtUdXBsZVN0cnVjdAAAAAABAAAH0AAAAAtUdXBsZVN0cnVjdAA="]), options); + this.options = options; } - parsers = { - hello: (result) => this.spec.funcResToNative("hello", result), - woid: () => { }, - val: (result) => this.spec.funcResToNative("val", result), - u32FailOnEven: (result) => { - if (result instanceof Err) - return result; - return new Ok(this.spec.funcResToNative("u32_fail_on_even", result)); - }, - u32: (result) => this.spec.funcResToNative("u32_", result), - i32: (result) => this.spec.funcResToNative("i32_", result), - i64: (result) => this.spec.funcResToNative("i64_", result), - struktHel: (result) => this.spec.funcResToNative("strukt_hel", result), - strukt: (result) => this.spec.funcResToNative("strukt", result), - simple: (result) => this.spec.funcResToNative("simple", result), - complex: (result) => this.spec.funcResToNative("complex", result), - addresse: (result) => this.spec.funcResToNative("addresse", result), - bytes: (result) => this.spec.funcResToNative("bytes", result), - bytesN: (result) => this.spec.funcResToNative("bytes_n", result), - card: (result) => this.spec.funcResToNative("card", result), - boolean: (result) => this.spec.funcResToNative("boolean", result), - not: (result) => this.spec.funcResToNative("not", result), - i128: (result) => this.spec.funcResToNative("i128", result), - u128: (result) => this.spec.funcResToNative("u128", result), - multiArgs: (result) => this.spec.funcResToNative("multi_args", result), - map: (result) => this.spec.funcResToNative("map", result), - vec: (result) => this.spec.funcResToNative("vec", result), - tuple: (result) => this.spec.funcResToNative("tuple", result), - option: (result) => this.spec.funcResToNative("option", result), - u256: (result) => this.spec.funcResToNative("u256", result), - i256: (result) => this.spec.funcResToNative("i256", result), - string: (result) => this.spec.funcResToNative("string", result), - tupleStrukt: (result) => this.spec.funcResToNative("tuple_strukt", result) - }; - txFromJSON = (json) => { - const { method, ...tx } = JSON.parse(json); - return AssembledTransaction.fromJSON({ - ...this.options, - method, - parseResultXdr: this.parsers[method], - }, tx); - }; fromJSON = { hello: (this.txFromJSON), woid: (this.txFromJSON), @@ -142,368 +92,4 @@ export class Contract { string: (this.txFromJSON), tupleStrukt: (this.txFromJSON) }; - /** -* Construct and simulate a hello transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - hello = async ({ hello }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'hello', - args: this.spec.funcArgsToScVals("hello", { hello }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['hello'], - }); - }; - /** -* Construct and simulate a woid transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - woid = async (options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'woid', - args: this.spec.funcArgsToScVals("woid", {}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['woid'], - }); - }; - /** -* Construct and simulate a val transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - val = async (options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'val', - args: this.spec.funcArgsToScVals("val", {}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['val'], - }); - }; - /** -* Construct and simulate a u32_fail_on_even transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - u32FailOnEven = async ({ u32_ }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'u32_fail_on_even', - args: this.spec.funcArgsToScVals("u32_fail_on_even", { u32_ }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['u32FailOnEven'], - }); - }; - /** -* Construct and simulate a u32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - u32 = async ({ u32_ }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'u32_', - args: this.spec.funcArgsToScVals("u32_", { u32_ }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['u32'], - }); - }; - /** -* Construct and simulate a i32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - i32 = async ({ i32_ }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'i32_', - args: this.spec.funcArgsToScVals("i32_", { i32_ }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['i32'], - }); - }; - /** -* Construct and simulate a i64_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - i64 = async ({ i64_ }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'i64_', - args: this.spec.funcArgsToScVals("i64_", { i64_ }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['i64'], - }); - }; - /** -* Construct and simulate a strukt_hel transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Example contract method which takes a struct -*/ - struktHel = async ({ strukt }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'strukt_hel', - args: this.spec.funcArgsToScVals("strukt_hel", { strukt }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['struktHel'], - }); - }; - /** -* Construct and simulate a strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - strukt = async ({ strukt }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'strukt', - args: this.spec.funcArgsToScVals("strukt", { strukt }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['strukt'], - }); - }; - /** -* Construct and simulate a simple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - simple = async ({ simple }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'simple', - args: this.spec.funcArgsToScVals("simple", { simple }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['simple'], - }); - }; - /** -* Construct and simulate a complex transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - complex = async ({ complex }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'complex', - args: this.spec.funcArgsToScVals("complex", { complex }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['complex'], - }); - }; - /** -* Construct and simulate a addresse transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - addresse = async ({ addresse }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'addresse', - args: this.spec.funcArgsToScVals("addresse", { addresse: new Address(addresse) }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['addresse'], - }); - }; - /** -* Construct and simulate a bytes transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - bytes = async ({ bytes }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'bytes', - args: this.spec.funcArgsToScVals("bytes", { bytes }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['bytes'], - }); - }; - /** -* Construct and simulate a bytes_n transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - bytesN = async ({ bytes_n }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'bytes_n', - args: this.spec.funcArgsToScVals("bytes_n", { bytes_n }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['bytesN'], - }); - }; - /** -* Construct and simulate a card transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - card = async ({ card }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'card', - args: this.spec.funcArgsToScVals("card", { card }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['card'], - }); - }; - /** -* Construct and simulate a boolean transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - boolean = async ({ boolean }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'boolean', - args: this.spec.funcArgsToScVals("boolean", { boolean }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['boolean'], - }); - }; - /** -* Construct and simulate a not transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Negates a boolean value -*/ - not = async ({ boolean }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'not', - args: this.spec.funcArgsToScVals("not", { boolean }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['not'], - }); - }; - /** -* Construct and simulate a i128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - i128 = async ({ i128 }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'i128', - args: this.spec.funcArgsToScVals("i128", { i128 }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['i128'], - }); - }; - /** -* Construct and simulate a u128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - u128 = async ({ u128 }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'u128', - args: this.spec.funcArgsToScVals("u128", { u128 }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['u128'], - }); - }; - /** -* Construct and simulate a multi_args transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - multiArgs = async ({ a, b }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'multi_args', - args: this.spec.funcArgsToScVals("multi_args", { a, b }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['multiArgs'], - }); - }; - /** -* Construct and simulate a map transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - map = async ({ map }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'map', - args: this.spec.funcArgsToScVals("map", { map }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['map'], - }); - }; - /** -* Construct and simulate a vec transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - vec = async ({ vec }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'vec', - args: this.spec.funcArgsToScVals("vec", { vec }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['vec'], - }); - }; - /** -* Construct and simulate a tuple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - tuple = async ({ tuple }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'tuple', - args: this.spec.funcArgsToScVals("tuple", { tuple }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['tuple'], - }); - }; - /** -* Construct and simulate a option transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Example of an optional argument -*/ - option = async ({ option }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'option', - args: this.spec.funcArgsToScVals("option", { option }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['option'], - }); - }; - /** -* Construct and simulate a u256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - u256 = async ({ u256 }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'u256', - args: this.spec.funcArgsToScVals("u256", { u256 }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['u256'], - }); - }; - /** -* Construct and simulate a i256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - i256 = async ({ i256 }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'i256', - args: this.spec.funcArgsToScVals("i256", { i256 }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['i256'], - }); - }; - /** -* Construct and simulate a string transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - string = async ({ string }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'string', - args: this.spec.funcArgsToScVals("string", { string }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['string'], - }); - }; - /** -* Construct and simulate a tuple_strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ - tupleStrukt = async ({ tuple_strukt }, options = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'tuple_strukt', - args: this.spec.funcArgsToScVals("tuple_strukt", { tuple_strukt }), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['tupleStrukt'], - }); - }; } diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/method-options.d.ts b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/method-options.d.ts deleted file mode 100644 index fc6b21d5d8..0000000000 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/method-options.d.ts +++ /dev/null @@ -1,47 +0,0 @@ -declare let responseTypes: 'simulated' | 'full' | undefined; -export type ResponseTypes = typeof responseTypes; -export type XDR_BASE64 = string; -export interface Wallet { - isConnected: () => Promise; - isAllowed: () => Promise; - getUserInfo: () => Promise<{ - publicKey?: string; - }>; - signTransaction: (tx: XDR_BASE64, opts?: { - network?: string; - networkPassphrase?: string; - accountToSign?: string; - }) => Promise; - signAuthEntry: (entryXdr: XDR_BASE64, opts?: { - accountToSign?: string; - }) => Promise; -} -export type ClassOptions = { - contractId: string; - networkPassphrase: string; - rpcUrl: string; - errorTypes?: Record; - /** - * A Wallet interface, such as Freighter, that has the methods `isConnected`, `isAllowed`, `getUserInfo`, and `signTransaction`. If not provided, will attempt to import and use Freighter. Example: - * - * @example - * ```ts - * import freighter from "@stellar/freighter-api"; - * import { Contract } from "test_custom_types"; - * const contract = new Contract({ - * …, - * wallet: freighter, - * }) - * ``` - */ - wallet?: Wallet; -}; -export type MethodOptions = { - /** - * The fee to pay for the transaction. Default: soroban-sdk's BASE_FEE ('100') - */ - fee?: number; -}; -export {}; diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/method-options.js b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/method-options.js deleted file mode 100644 index 00ad9d3cf4..0000000000 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/esm/method-options.js +++ /dev/null @@ -1,3 +0,0 @@ -// defined this way so typeahead shows full union, not named alias -let responseTypes; -export {}; diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/types/assembled-tx.d.ts b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/types/assembled-tx.d.ts deleted file mode 100644 index 1d5e6f5ee8..0000000000 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/types/assembled-tx.d.ts +++ /dev/null @@ -1,184 +0,0 @@ -import { Account, Address, Operation, SorobanRpc, xdr } from "@stellar/stellar-sdk"; -import type { Memo, MemoType, Transaction } from "@stellar/stellar-sdk"; -import type { ClassOptions, MethodOptions, Wallet, XDR_BASE64 } from "./method-options.js"; -export type Tx = Transaction, Operation[]>; -export declare class ExpiredStateError extends Error { -} -export declare class NeedsMoreSignaturesError extends Error { -} -export declare class WalletDisconnectedError extends Error { -} -export declare class SendResultOnlyError extends Error { -} -export declare class SendFailedError extends Error { -} -export declare class NoUnsignedNonInvokerAuthEntriesError extends Error { -} -type SendTx = SorobanRpc.Api.SendTransactionResponse; -type GetTx = SorobanRpc.Api.GetTransactionResponse; -export type u32 = number; -export type i32 = number; -export type u64 = bigint; -export type i64 = bigint; -export type u128 = bigint; -export type i128 = bigint; -export type u256 = bigint; -export type i256 = bigint; -export type Option = T | undefined; -export type Typepoint = bigint; -export type Duration = bigint; -export { Address }; -export interface Error_ { - message: string; -} -export interface Result { - unwrap(): T; - unwrapErr(): E; - isOk(): boolean; - isErr(): boolean; -} -export declare class Ok implements Result { - readonly value: T; - constructor(value: T); - unwrapErr(): E; - unwrap(): T; - isOk(): boolean; - isErr(): boolean; -} -export declare class Err implements Result { - readonly error: E; - constructor(error: E); - unwrapErr(): E; - unwrap(): never; - isOk(): boolean; - isErr(): boolean; -} -export declare const contractErrorPattern: RegExp; -type AssembledTransactionOptions = MethodOptions & ClassOptions & { - method: string; - args?: any[]; - parseResultXdr: (xdr: string | xdr.ScVal | Err) => T; -}; -export declare const NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; -export declare class AssembledTransaction { - options: AssembledTransactionOptions; - raw: Tx; - private simulation?; - private simulationResult?; - private simulationTransactionData?; - private server; - toJSON(): string; - static fromJSON(options: Omit, 'args'>, { tx, simulationResult, simulationTransactionData }: { - tx: XDR_BASE64; - simulationResult: { - auth: XDR_BASE64[]; - retval: XDR_BASE64; - }; - simulationTransactionData: XDR_BASE64; - }): AssembledTransaction; - private constructor(); - static fromSimulation(options: AssembledTransactionOptions): Promise>; - simulate: () => Promise; - get simulationData(): { - result: SorobanRpc.Api.SimulateHostFunctionResult; - transactionData: xdr.SorobanTransactionData; - }; - get result(): T; - parseError(errorMessage: string): Err | undefined; - getWallet: () => Promise; - getPublicKey: () => Promise; - /** - * Get account details from the Soroban network for the publicKey currently - * selected in user's wallet. If not connected to Freighter, use placeholder - * null account. - */ - getAccount: () => Promise; - /** - * Sign the transaction with the `wallet` (default Freighter), then send to - * the network and return a `SentTransaction` that keeps track of all the - * attempts to send and fetch the transaction from the network. - */ - signAndSend: ({ secondsToWait, force }?: { - /** - * Wait `secondsToWait` seconds (default: 10) for both the transaction to SEND successfully (will keep trying if the server returns `TRY_AGAIN_LATER`), as well as for the transaction to COMPLETE (will keep checking if the server returns `PENDING`). - */ - secondsToWait?: number | undefined; - /** - * If `true`, sign and send the transaction even if it is a read call. - */ - force?: boolean | undefined; - }) => Promise>; - getStorageExpiration: () => Promise; - /** - * Get a list of accounts, other than the invoker of the simulation, that - * need to sign auth entries in this transaction. - * - * Soroban allows multiple people to sign a transaction. Someone needs to - * sign the final transaction envelope; this person/account is called the - * _invoker_, or _source_. Other accounts might need to sign individual auth - * entries in the transaction, if they're not also the invoker. - * - * This function returns a list of accounts that need to sign auth entries, - * assuming that the same invoker/source account will sign the final - * transaction envelope as signed the initial simulation. - * - * One at a time, for each public key in this array, you will need to - * serialize this transaction with `toJSON`, send to the owner of that key, - * deserialize the transaction with `txFromJson`, and call - * {@link signAuthEntries}. Then re-serialize and send to the next account - * in this list. - */ - needsNonInvokerSigningBy: ({ includeAlreadySigned, }?: { - /** - * Whether or not to include auth entries that have already been signed. Default: false - */ - includeAlreadySigned?: boolean | undefined; - }) => Promise; - preImageFor(entry: xdr.SorobanAuthorizationEntry, signatureExpirationLedger: number): xdr.HashIdPreimage; - /** - * If {@link needsNonInvokerSigningBy} returns a non-empty list, you can serialize - * the transaction with `toJSON`, send it to the owner of one of the public keys - * in the map, deserialize with `txFromJSON`, and call this method on their - * machine. Internally, this will use `signAuthEntry` function from connected - * `wallet` for each. - * - * Then, re-serialize the transaction and either send to the next - * `needsNonInvokerSigningBy` owner, or send it back to the original account - * who simulated the transaction so they can {@link sign} the transaction - * envelope and {@link send} it to the network. - * - * Sending to all `needsNonInvokerSigningBy` owners in parallel is not currently - * supported! - */ - signAuthEntries: (expiration?: number | Promise) => Promise; - get isReadCall(): boolean; - hasRealInvoker: () => Promise; -} -/** - * A transaction that has been sent to the Soroban network. This happens in two steps: - * - * 1. `sendTransaction`: initial submission of the transaction to the network. - * This step can run into problems, and will be retried with exponential - * backoff if it does. See all attempts in `sendTransactionResponseAll` and the - * most recent attempt in `sendTransactionResponse`. - * 2. `getTransaction`: once the transaction has been submitted to the network - * successfully, you need to wait for it to finalize to get the results of the - * transaction. This step can also run into problems, and will be retried with - * exponential backoff if it does. See all attempts in - * `getTransactionResponseAll` and the most recent attempt in - * `getTransactionResponse`. - */ -declare class SentTransaction { - options: AssembledTransactionOptions; - assembled: AssembledTransaction; - server: SorobanRpc.Server; - signed: Tx; - sendTransactionResponse?: SendTx; - sendTransactionResponseAll?: SendTx[]; - getTransactionResponse?: GetTx; - getTransactionResponseAll?: GetTx[]; - constructor(options: AssembledTransactionOptions, assembled: AssembledTransaction); - static init: (options: AssembledTransactionOptions, assembled: AssembledTransaction, secondsToWait?: number) => Promise>; - private send; - get result(): T; -} diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/types/index.d.ts b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/types/index.d.ts index 66d3d59597..58a5712000 100644 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/types/index.d.ts +++ b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/types/index.d.ts @@ -1,10 +1,10 @@ -import { ContractSpec } from '@stellar/stellar-sdk'; import { Buffer } from "buffer"; -import { AssembledTransaction, Ok, Err } from './assembled-tx.js'; -import type { u32, i32, i64, i128, Option, Error_ } from './assembled-tx.js'; -import type { ClassOptions } from './method-options.js'; -export * from './assembled-tx.js'; -export * from './method-options.js'; +import { AssembledTransaction, ContractClient, ContractClientOptions } from '@stellar/stellar-sdk/lib/contract_client/index.js'; +import type { u32, i32, i64, u128, i128, u256, i256, Option } from '@stellar/stellar-sdk/lib/contract_client'; +import { Result } from '@stellar/stellar-sdk/lib/rust_types/index.js'; +export * from '@stellar/stellar-sdk'; +export * from '@stellar/stellar-sdk/lib/contract_client/index.js'; +export * from '@stellar/stellar-sdk/lib/rust_types/index.js'; export declare const networks: { readonly futurenet: { readonly networkPassphrase: "Test SDF Future Network ; October 2022"; @@ -12,25 +12,13 @@ export declare const networks: { }; }; /** - This is from the rust doc above the struct Test - */ + * This is from the rust doc above the struct Test + */ export interface Test { - /** - - */ a: u32; - /** - - */ b: boolean; - /** - - */ c: string; } -/** - - */ export type SimpleEnum = { tag: "First"; values: void; @@ -41,21 +29,12 @@ export type SimpleEnum = { tag: "Third"; values: void; }; -/** - - */ export declare enum RoyalCard { Jack = 11, Queen = 12, King = 13 } -/** - - */ export type TupleStruct = readonly [Test, SimpleEnum]; -/** - - */ export type ComplexEnum = { tag: "Struct"; values: readonly [Test]; @@ -72,353 +51,576 @@ export type ComplexEnum = { tag: "Void"; values: void; }; -/** - - */ export declare const Errors: { 1: { message: string; }; }; -export declare class Contract { - readonly options: ClassOptions; - spec: ContractSpec; - constructor(options: ClassOptions); - private readonly parsers; - private txFromJSON; - readonly fromJSON: { - hello: (json: string) => AssembledTransaction; - woid: (json: string) => AssembledTransaction; - val: (json: string) => AssembledTransaction; - u32FailOnEven: (json: string) => AssembledTransaction | Ok>; - u32: (json: string) => AssembledTransaction; - i32: (json: string) => AssembledTransaction; - i64: (json: string) => AssembledTransaction; - struktHel: (json: string) => AssembledTransaction; - strukt: (json: string) => AssembledTransaction; - simple: (json: string) => AssembledTransaction; - complex: (json: string) => AssembledTransaction; - addresse: (json: string) => AssembledTransaction; - bytes: (json: string) => AssembledTransaction; - bytesN: (json: string) => AssembledTransaction; - card: (json: string) => AssembledTransaction; - boolean: (json: string) => AssembledTransaction; - not: (json: string) => AssembledTransaction; - i128: (json: string) => AssembledTransaction; - u128: (json: string) => AssembledTransaction; - multiArgs: (json: string) => AssembledTransaction; - map: (json: string) => AssembledTransaction>; - vec: (json: string) => AssembledTransaction; - tuple: (json: string) => AssembledTransaction; - option: (json: string) => AssembledTransaction>; - u256: (json: string) => AssembledTransaction; - i256: (json: string) => AssembledTransaction; - string: (json: string) => AssembledTransaction; - tupleStrukt: (json: string) => AssembledTransaction; - }; +export interface Client { /** -* Construct and simulate a hello transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a hello transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ hello: ({ hello }: { hello: string; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a woid transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a woid transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ woid: (options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a val transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a val transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ val: (options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a u32_fail_on_even transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a u32_fail_on_even transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ u32FailOnEven: ({ u32_ }: { u32_: u32; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise | Ok>>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>>; /** -* Construct and simulate a u32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a u32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ u32: ({ u32_ }: { u32_: u32; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a i32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a i32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ i32: ({ i32_ }: { i32_: i32; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a i64_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a i64_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ i64: ({ i64_ }: { i64_: i64; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a strukt_hel transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Example contract method which takes a struct -*/ + * Construct and simulate a strukt_hel transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. * + * Example contract method which takes a struct + */ struktHel: ({ strukt }: { strukt: Test; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>>; /** -* Construct and simulate a strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ strukt: ({ strukt }: { strukt: Test; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a simple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a simple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ simple: ({ simple }: { simple: SimpleEnum; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a complex transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a complex transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ complex: ({ complex }: { complex: ComplexEnum; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a addresse transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a addresse transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ addresse: ({ addresse }: { addresse: string; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a bytes transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a bytes transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ bytes: ({ bytes }: { bytes: Buffer; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a bytes_n transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a bytes_n transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ bytesN: ({ bytes_n }: { bytes_n: Buffer; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a card transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a card transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ card: ({ card }: { card: RoyalCard; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a boolean transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a boolean transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ boolean: ({ boolean }: { boolean: boolean; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a not transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Negates a boolean value -*/ + * Construct and simulate a not transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. * + * Negates a boolean value + */ not: ({ boolean }: { boolean: boolean; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a i128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a i128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ i128: ({ i128 }: { - i128: bigint; + i128: i128; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a u128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a u128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ u128: ({ u128 }: { - u128: bigint; + u128: u128; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a multi_args transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a multi_args transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ multiArgs: ({ a, b }: { a: u32; b: boolean; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a map transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a map transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ map: ({ map }: { map: Map; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>>; /** -* Construct and simulate a vec transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a vec transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ vec: ({ vec }: { vec: Array; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>>; /** -* Construct and simulate a tuple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a tuple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ tuple: ({ tuple }: { tuple: readonly [string, u32]; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a option transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Example of an optional argument -*/ + * Construct and simulate a option transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. * + * Example of an optional argument + */ option: ({ option }: { option: Option; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>>; /** -* Construct and simulate a u256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a u256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ u256: ({ u256 }: { - u256: bigint; + u256: u256; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a i256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a i256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ i256: ({ i256 }: { - i256: bigint; + i256: i256; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; - }) => Promise>; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>; /** -* Construct and simulate a string transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a string transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ string: ({ string }: { string: string; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; /** -* Construct and simulate a tuple_strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. -*/ + * Construct and simulate a tuple_strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ tupleStrukt: ({ tuple_strukt }: { tuple_strukt: TupleStruct; }, options?: { /** - * The fee to pay for the transaction. Default: 100. + * The fee to pay for the transaction. Default: BASE_FEE */ fee?: number; + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; }) => Promise>; } +export declare class Client extends ContractClient { + readonly options: ContractClientOptions; + constructor(options: ContractClientOptions); + readonly fromJSON: { + hello: (json: string) => AssembledTransaction; + woid: (json: string) => AssembledTransaction; + val: (json: string) => AssembledTransaction; + u32FailOnEven: (json: string) => AssembledTransaction>; + u32: (json: string) => AssembledTransaction; + i32: (json: string) => AssembledTransaction; + i64: (json: string) => AssembledTransaction; + struktHel: (json: string) => AssembledTransaction; + strukt: (json: string) => AssembledTransaction; + simple: (json: string) => AssembledTransaction; + complex: (json: string) => AssembledTransaction; + addresse: (json: string) => AssembledTransaction; + bytes: (json: string) => AssembledTransaction; + bytesN: (json: string) => AssembledTransaction; + card: (json: string) => AssembledTransaction; + boolean: (json: string) => AssembledTransaction; + not: (json: string) => AssembledTransaction; + i128: (json: string) => AssembledTransaction; + u128: (json: string) => AssembledTransaction; + multiArgs: (json: string) => AssembledTransaction; + map: (json: string) => AssembledTransaction>; + vec: (json: string) => AssembledTransaction; + tuple: (json: string) => AssembledTransaction; + option: (json: string) => AssembledTransaction>; + u256: (json: string) => AssembledTransaction; + i256: (json: string) => AssembledTransaction; + string: (json: string) => AssembledTransaction; + tupleStrukt: (json: string) => AssembledTransaction; + }; +} diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/types/method-options.d.ts b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/types/method-options.d.ts deleted file mode 100644 index fc6b21d5d8..0000000000 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/dist/types/method-options.d.ts +++ /dev/null @@ -1,47 +0,0 @@ -declare let responseTypes: 'simulated' | 'full' | undefined; -export type ResponseTypes = typeof responseTypes; -export type XDR_BASE64 = string; -export interface Wallet { - isConnected: () => Promise; - isAllowed: () => Promise; - getUserInfo: () => Promise<{ - publicKey?: string; - }>; - signTransaction: (tx: XDR_BASE64, opts?: { - network?: string; - networkPassphrase?: string; - accountToSign?: string; - }) => Promise; - signAuthEntry: (entryXdr: XDR_BASE64, opts?: { - accountToSign?: string; - }) => Promise; -} -export type ClassOptions = { - contractId: string; - networkPassphrase: string; - rpcUrl: string; - errorTypes?: Record; - /** - * A Wallet interface, such as Freighter, that has the methods `isConnected`, `isAllowed`, `getUserInfo`, and `signTransaction`. If not provided, will attempt to import and use Freighter. Example: - * - * @example - * ```ts - * import freighter from "@stellar/freighter-api"; - * import { Contract } from "test_custom_types"; - * const contract = new Contract({ - * …, - * wallet: freighter, - * }) - * ``` - */ - wallet?: Wallet; -}; -export type MethodOptions = { - /** - * The fee to pay for the transaction. Default: soroban-sdk's BASE_FEE ('100') - */ - fee?: number; -}; -export {}; diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/package-lock.json b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/package-lock.json index 44332a410c..2261fc9671 100644 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/package-lock.json +++ b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/package-lock.json @@ -8,8 +8,8 @@ "name": "test_custom_types", "version": "0.0.0", "dependencies": { - "@stellar/freighter-api": "1.7.1", - "@stellar/stellar-sdk": "11.2.0", + "@stellar/freighter-api": "2.0.0", + "@stellar/stellar-sdk": "stellar/js-stellar-sdk#bindings", "buffer": "6.0.3" }, "devDependencies": { @@ -17,42 +17,44 @@ } }, "node_modules/@stellar/freighter-api": { - "version": "1.7.1", - "resolved": "https://registry.npmjs.org/@stellar/freighter-api/-/freighter-api-1.7.1.tgz", - "integrity": "sha512-XvPO+XgEbkeP0VhP0U1edOkds+rGS28+y8GRGbCVXeZ9ZslbWqRFQoETAdX8IXGuykk2ib/aPokiLc5ZaWYP7w==" + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@stellar/freighter-api/-/freighter-api-2.0.0.tgz", + "integrity": "sha512-j/R7MLPL8S3QhwOEdAxSl7MgWBTXWlOXQKQyXR8mPk1JMKKR4tF8e4U+Fs9TPQH0HZoYqfVDvLOOUrTMMY058Q==" }, "node_modules/@stellar/js-xdr": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@stellar/js-xdr/-/js-xdr-3.0.1.tgz", - "integrity": "sha512-dp5Eh7Nr1YjiIeqpdkj2cQYxfoPudDAH3ck8MWggp48Htw66Z/hUssNYUQG/OftLjEmHT90Z/dtey2Y77DOxIw==" + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@stellar/js-xdr/-/js-xdr-3.1.0.tgz", + "integrity": "sha512-mYTyFnhgyQgyvpAYZRO1LurUn2MxcIZRj74zZz/BxKEk7zrL4axhQ1ez0HL2BRi0wlG6cHn5BeD/t9Xcyp7CSQ==" }, "node_modules/@stellar/stellar-base": { - "version": "10.0.1", - "resolved": "https://registry.npmjs.org/@stellar/stellar-base/-/stellar-base-10.0.1.tgz", - "integrity": "sha512-BDbx7VHOEQh+4J3Q+gStNXgPaNckVFmD4aOlBBGwxlF6vPFmVnW8IoJdkX7T58zpX55eWI6DXvEhDBlrqTlhAQ==", + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/@stellar/stellar-base/-/stellar-base-11.0.0.tgz", + "integrity": "sha512-KPTjaWJCG2m7hMCPRWFGGPaG5qOkgPLWvFVOhe1HUy7dlE4MxxPfdusz0mcLkf6VT7doqhLB1rIt0D9M2GgQcQ==", "dependencies": { - "@stellar/js-xdr": "^3.0.1", + "@stellar/js-xdr": "^3.1.0", "base32.js": "^0.1.0", "bignumber.js": "^9.1.2", "buffer": "^6.0.3", "sha.js": "^2.3.6", - "tweetnacl": "^1.0.3" + "tweetnacl": "^1.0.3", + "typescript": "^5.3.3" }, "optionalDependencies": { - "sodium-native": "^4.0.1" + "sodium-native": "^4.0.8" } }, "node_modules/@stellar/stellar-sdk": { - "version": "11.2.0", - "resolved": "https://registry.npmjs.org/@stellar/stellar-sdk/-/stellar-sdk-11.2.0.tgz", - "integrity": "sha512-qInRR+mLLl9O/AI6Q+Sr19RZeYJtlNoJQJi3pch5BYoMvVhjO8IU8AhHADP//Zmc2osyogwPuqXBiFdaGlfHWA==", + "version": "11.2.2", + "resolved": "git+ssh://git@github.com/stellar/js-stellar-sdk.git#bdf74951f89bbc9bd48179b4a7a4ad33db570643", + "license": "Apache-2.0", "dependencies": { - "@stellar/stellar-base": "10.0.1", - "axios": "^1.6.5", + "@stellar/stellar-base": "^11.0.0", + "axios": "^1.6.7", "bignumber.js": "^9.1.2", "eventsource": "^2.0.2", "randombytes": "^2.1.0", "toml": "^3.0.0", + "typescript": "^5.3.3", "urijs": "^1.19.1" } }, @@ -62,9 +64,9 @@ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" }, "node_modules/axios": { - "version": "1.6.5", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.5.tgz", - "integrity": "sha512-Ii012v05KEVuUoFWmMW/UQv9aRIc3ZwkWDcM+h5Il8izZCtRVpDUfwpoFf7eOtajT3QiGR4yDUx7lPqHJULgbg==", + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.7.tgz", + "integrity": "sha512-/hDJGff6/c7u0hDkvkGxR/oy6CbCs8ziCsC7SqmhjfozqiJGc8Z11wrv9z9lYfY4K8l+H9TpjcMDX0xOZmx+RA==", "dependencies": { "follow-redirects": "^1.15.4", "form-data": "^4.0.0", @@ -157,9 +159,9 @@ } }, "node_modules/follow-redirects": { - "version": "1.15.4", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.4.tgz", - "integrity": "sha512-Cr4D/5wlrb0z9dgERpUL3LrmPKVDsETIJhaCMeDfuFYcqa5bldGV6wBsAN6X/vxlXQtFBMrXdXxdL8CbDTGniw==", + "version": "1.15.5", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz", + "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==", "funding": [ { "type": "individual", @@ -287,9 +289,9 @@ } }, "node_modules/sodium-native": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/sodium-native/-/sodium-native-4.0.5.tgz", - "integrity": "sha512-YGimGhy7Ho6pTAAvuNdn3Tv9C2MD7HP89X1omReHat0Fd1mMnapGqwzb5YoHTAbIEh8tQmKP6+uLlwYCkf+EOA==", + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/sodium-native/-/sodium-native-4.0.10.tgz", + "integrity": "sha512-vrJQt4gASntDbnltRRk9vN4rks1SehjM12HkqQtu250JtWT+/lo8oEOa1HvSq3+8hzJdYcCJuLR5qRGxoRDjAg==", "hasInstallScript": true, "optional": true, "dependencies": { @@ -310,7 +312,6 @@ "version": "5.3.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.3.3.tgz", "integrity": "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==", - "dev": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/package.json b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/package.json index 1f63968ae7..042f8c02b9 100644 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/package.json +++ b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/package.json @@ -2,9 +2,9 @@ "version": "0.0.0", "name": "test_custom_types", "dependencies": { - "@stellar/freighter-api": "1.7.1", + "@stellar/freighter-api": "2.0.0", "buffer": "6.0.3", - "@stellar/stellar-sdk": "11.2.0" + "@stellar/stellar-sdk": "stellar/js-stellar-sdk#bindings" }, "scripts": { "build": "node ./scripts/build.mjs" diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/src/assembled-tx.ts b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/src/assembled-tx.ts deleted file mode 100644 index f4f892d4d3..0000000000 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/src/assembled-tx.ts +++ /dev/null @@ -1,664 +0,0 @@ -import { - Account, - Address, - Contract, - Operation, - SorobanRpc, - StrKey, - TimeoutInfinite, - TransactionBuilder, - authorizeEntry, - hash, - nativeToScVal, - xdr, - BASE_FEE, -} from "@stellar/stellar-sdk"; -import type { Memo, MemoType, Transaction } from "@stellar/stellar-sdk"; -import { Buffer } from "buffer"; -import type { - ClassOptions, - MethodOptions, - Wallet, - XDR_BASE64, -} from "./method-options.js"; - -export type Tx = Transaction, Operation[]> - -export class ExpiredStateError extends Error { } -export class NeedsMoreSignaturesError extends Error { } -export class WalletDisconnectedError extends Error { } -export class SendResultOnlyError extends Error { } -export class SendFailedError extends Error { } -export class NoUnsignedNonInvokerAuthEntriesError extends Error { } - -type SendTx = SorobanRpc.Api.SendTransactionResponse; -type GetTx = SorobanRpc.Api.GetTransactionResponse; - -export type u32 = number; -export type i32 = number; -export type u64 = bigint; -export type i64 = bigint; -export type u128 = bigint; -export type i128 = bigint; -export type u256 = bigint; -export type i256 = bigint; -export type Option = T | undefined; -export type Typepoint = bigint; -export type Duration = bigint; -export {Address}; - -/// Error interface containing the error message -export interface Error_ { message: string }; - -export interface Result { - unwrap(): T, - unwrapErr(): E, - isOk(): boolean, - isErr(): boolean, -}; - -export class Ok implements Result { - constructor(readonly value: T) { } - unwrapErr(): E { - throw new Error('No error'); - } - unwrap(): T { - return this.value; - } - - isOk(): boolean { - return true; - } - - isErr(): boolean { - return !this.isOk() - } -} - -export class Err implements Result { - constructor(readonly error: E) { } - unwrapErr(): E { - return this.error; - } - unwrap(): never { - throw new Error(this.error.message); - } - - isOk(): boolean { - return false; - } - - isErr(): boolean { - return !this.isOk() - } -} - -export const contractErrorPattern = /Error\(Contract, #(\d+)\)/; - -type AssembledTransactionOptions = MethodOptions & - ClassOptions & { - method: string; - args?: any[]; - parseResultXdr: (xdr: string | xdr.ScVal | Err) => T; - }; - -export const NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF" - -export class AssembledTransaction { - public raw: Tx - private simulation?: SorobanRpc.Api.SimulateTransactionResponse - private simulationResult?: SorobanRpc.Api.SimulateHostFunctionResult - private simulationTransactionData?: xdr.SorobanTransactionData - private server: SorobanRpc.Server - - toJSON() { - return JSON.stringify({ - method: this.options.method, - tx: this.raw?.toXDR(), - simulationResult: { - auth: this.simulationData.result.auth.map(a => a.toXDR('base64')), - retval: this.simulationData.result.retval.toXDR('base64'), - }, - simulationTransactionData: this.simulationData.transactionData.toXDR('base64'), - }) - } - - static fromJSON( - options: Omit, 'args'>, - { tx, simulationResult, simulationTransactionData }: - { - tx: XDR_BASE64, - simulationResult: { - auth: XDR_BASE64[], - retval: XDR_BASE64, - }, - simulationTransactionData: XDR_BASE64, - } - ): AssembledTransaction { - const txn = new AssembledTransaction(options) - txn.raw = TransactionBuilder.fromXDR(tx, options.networkPassphrase) as Tx - txn.simulationResult = { - auth: simulationResult.auth.map(a => xdr.SorobanAuthorizationEntry.fromXDR(a, 'base64')), - retval: xdr.ScVal.fromXDR(simulationResult.retval, 'base64'), - } - txn.simulationTransactionData = xdr.SorobanTransactionData.fromXDR(simulationTransactionData, 'base64') - return txn - } - - private constructor(public options: AssembledTransactionOptions) { - this.server = new SorobanRpc.Server(this.options.rpcUrl, { - allowHttp: this.options.rpcUrl.startsWith("http://"), - }); - } - - static async fromSimulation(options: AssembledTransactionOptions): Promise> { - const tx = new AssembledTransaction(options) - const contract = new Contract(options.contractId); - - tx.raw = new TransactionBuilder(await tx.getAccount(), { - fee: options.fee?.toString(10) ?? BASE_FEE, - networkPassphrase: options.networkPassphrase, - }) - .addOperation(contract.call(options.method, ...(options.args ?? []))) - .setTimeout(TimeoutInfinite) - .build(); - - return await tx.simulate() - } - - simulate = async (): Promise => { - if (!this.raw) throw new Error('Transaction has not yet been assembled') - this.simulation = await this.server.simulateTransaction(this.raw); - - if (SorobanRpc.Api.isSimulationSuccess(this.simulation)) { - this.raw = SorobanRpc.assembleTransaction( - this.raw, - this.simulation - ).build() - } - - return this - } - - get simulationData(): { - result: SorobanRpc.Api.SimulateHostFunctionResult - transactionData: xdr.SorobanTransactionData - } { - if (this.simulationResult && this.simulationTransactionData) { - return { - result: this.simulationResult, - transactionData: this.simulationTransactionData, - } - } - // else, we know we just did the simulation on this machine - const simulation = this.simulation! - if (SorobanRpc.Api.isSimulationError(simulation)) { - throw new Error(`Transaction simulation failed: "${simulation.error}"`) - } - - if (SorobanRpc.Api.isSimulationRestore(simulation)) { - throw new ExpiredStateError(`You need to restore some contract state before you can invoke this method. ${JSON.stringify(simulation, null, 2)}`) - } - - if (!simulation.result) { - throw new Error(`Expected an invocation simulation, but got no 'result' field. Simulation: ${JSON.stringify(simulation, null, 2)}`) - } - - // add to object for serialization & deserialization - this.simulationResult = simulation.result - this.simulationTransactionData = simulation.transactionData.build() - - return { - result: this.simulationResult, - transactionData: this.simulationTransactionData!, - } - } - - get result(): T { - try { - return this.options.parseResultXdr(this.simulationData.result.retval) - } catch (e) { - let err = this.parseError(e.toString()) - if (err) return err as T - throw e - } - } - - parseError(errorMessage: string): Err | undefined { - if (!this.options.errorTypes) return - const match = errorMessage.match(contractErrorPattern) - if (!match) return - let i = parseInt(match[1], 10) - let err = this.options.errorTypes[i] - if (err) return new Err(err) - } - - getWallet = async (): Promise => { - return this.options.wallet ?? (await import("@stellar/freighter-api")).default - } - - getPublicKey = async (): Promise => { - const wallet = await this.getWallet() - if (await wallet.isConnected() && await wallet.isAllowed()) { - return (await wallet.getUserInfo()).publicKey - } - } - - /** - * Get account details from the Soroban network for the publicKey currently - * selected in user's wallet. If not connected to Freighter, use placeholder - * null account. - */ - getAccount = async (): Promise => { - const publicKey = await this.getPublicKey() - return publicKey - ? await this.server.getAccount(publicKey) - : new Account(NULL_ACCOUNT, "0") - } - - /** - * Sign the transaction with the `wallet` (default Freighter), then send to - * the network and return a `SentTransaction` that keeps track of all the - * attempts to send and fetch the transaction from the network. - */ - signAndSend = async ({ secondsToWait = 10, force = false }: { - /** - * Wait `secondsToWait` seconds (default: 10) for both the transaction to SEND successfully (will keep trying if the server returns `TRY_AGAIN_LATER`), as well as for the transaction to COMPLETE (will keep checking if the server returns `PENDING`). - */ - secondsToWait?: number - /** - * If `true`, sign and send the transaction even if it is a read call. - */ - force?: boolean - } = {}): Promise> => { - if (!this.raw) { - throw new Error('Transaction has not yet been simulated') - } - - if (!force && this.isReadCall) { - throw new Error('This is a read call. It requires no signature or sending. Use `force: true` to sign and send anyway.') - } - - if (!await this.hasRealInvoker()) { - throw new WalletDisconnectedError('Wallet is not connected') - } - - if (this.raw.source !== (await this.getAccount()).accountId()) { - throw new Error(`You must submit the transaction with the account that originally created it. Please switch to the wallet with "${this.raw.source}" as its public key.`) - } - - if ((await this.needsNonInvokerSigningBy()).length) { - throw new NeedsMoreSignaturesError( - 'Transaction requires more signatures. See `needsNonInvokerSigningBy` for details.' - ) - } - - return await SentTransaction.init(this.options, this, secondsToWait); - } - - getStorageExpiration = async () => { - const entryRes = await this.server.getLedgerEntries( - new Contract(this.options.contractId).getFootprint() - ) - if ( - !entryRes.entries || - !entryRes.entries.length || - !entryRes.entries[0].liveUntilLedgerSeq - ) throw new Error('failed to get ledger entry') - return entryRes.entries[0].liveUntilLedgerSeq - } - - /** - * Get a list of accounts, other than the invoker of the simulation, that - * need to sign auth entries in this transaction. - * - * Soroban allows multiple people to sign a transaction. Someone needs to - * sign the final transaction envelope; this person/account is called the - * _invoker_, or _source_. Other accounts might need to sign individual auth - * entries in the transaction, if they're not also the invoker. - * - * This function returns a list of accounts that need to sign auth entries, - * assuming that the same invoker/source account will sign the final - * transaction envelope as signed the initial simulation. - * - * One at a time, for each public key in this array, you will need to - * serialize this transaction with `toJSON`, send to the owner of that key, - * deserialize the transaction with `txFromJson`, and call - * {@link signAuthEntries}. Then re-serialize and send to the next account - * in this list. - */ - needsNonInvokerSigningBy = async ({ - includeAlreadySigned = false, - }: { - /** - * Whether or not to include auth entries that have already been signed. Default: false - */ - includeAlreadySigned?: boolean - } = {}): Promise => { - if (!this.raw) { - throw new Error('Transaction has not yet been simulated') - } - - // We expect that any transaction constructed by these libraries has a - // single operation, which is an InvokeHostFunction operation. The host - // function being invoked is the contract method call. - if (!("operations" in this.raw)) { - throw new Error( - `Unexpected Transaction type; no operations: ${JSON.stringify(this.raw) - }` - ) - } - const rawInvokeHostFunctionOp = this.raw - .operations[0] as Operation.InvokeHostFunction - - return [...new Set((rawInvokeHostFunctionOp.auth ?? []).filter(entry => - entry.credentials().switch() === - xdr.SorobanCredentialsType.sorobanCredentialsAddress() && - ( - includeAlreadySigned || - entry.credentials().address().signature().switch().name === 'scvVoid' - ) - ).map(entry => StrKey.encodeEd25519PublicKey( - entry.credentials().address().address().accountId().ed25519() - )))] - } - - preImageFor( - entry: xdr.SorobanAuthorizationEntry, - signatureExpirationLedger: number - ): xdr.HashIdPreimage { - const addrAuth = entry.credentials().address() - return xdr.HashIdPreimage.envelopeTypeSorobanAuthorization( - new xdr.HashIdPreimageSorobanAuthorization({ - networkId: hash(Buffer.from(this.options.networkPassphrase)), - nonce: addrAuth.nonce(), - invocation: entry.rootInvocation(), - signatureExpirationLedger, - }), - ) - } - - /** - * If {@link needsNonInvokerSigningBy} returns a non-empty list, you can serialize - * the transaction with `toJSON`, send it to the owner of one of the public keys - * in the map, deserialize with `txFromJSON`, and call this method on their - * machine. Internally, this will use `signAuthEntry` function from connected - * `wallet` for each. - * - * Then, re-serialize the transaction and either send to the next - * `needsNonInvokerSigningBy` owner, or send it back to the original account - * who simulated the transaction so they can {@link sign} the transaction - * envelope and {@link send} it to the network. - * - * Sending to all `needsNonInvokerSigningBy` owners in parallel is not currently - * supported! - */ - signAuthEntries = async ( - /** - * When to set each auth entry to expire. Could be any number of blocks in - * the future. Can be supplied as a promise or a raw number. Default: - * contract's current `persistent` storage expiration date/ledger - * number/block. - */ - expiration: number | Promise = this.getStorageExpiration() - ): Promise => { - if (!this.raw) throw new Error('Transaction has not yet been assembled or simulated') - const needsNonInvokerSigningBy = await this.needsNonInvokerSigningBy() - - if (!needsNonInvokerSigningBy) throw new NoUnsignedNonInvokerAuthEntriesError('No unsigned non-invoker auth entries; maybe you already signed?') - const publicKey = await this.getPublicKey() - if (!publicKey) throw new Error('Could not get public key from wallet; maybe Freighter is not signed in?') - if (needsNonInvokerSigningBy.indexOf(publicKey) === -1) throw new Error(`No auth entries for public key "${publicKey}"`) - const wallet = await this.getWallet() - - const rawInvokeHostFunctionOp = this.raw - .operations[0] as Operation.InvokeHostFunction - - const authEntries = rawInvokeHostFunctionOp.auth ?? [] - - for (const [i, entry] of authEntries.entries()) { - if ( - entry.credentials().switch() !== - xdr.SorobanCredentialsType.sorobanCredentialsAddress() - ) { - // if the invoker/source account, then the entry doesn't need explicit - // signature, since the tx envelope is already signed by the source - // account, so only check for sorobanCredentialsAddress - continue - } - const pk = StrKey.encodeEd25519PublicKey( - entry.credentials().address().address().accountId().ed25519() - ) - - // this auth entry needs to be signed by a different account - // (or maybe already was!) - if (pk !== publicKey) continue - - authEntries[i] = await authorizeEntry( - entry, - async preimage => Buffer.from( - await wallet.signAuthEntry(preimage.toXDR('base64')), - 'base64' - ), - await expiration, - this.options.networkPassphrase - ) - } - } - - get isReadCall(): boolean { - const authsCount = this.simulationData.result.auth.length; - const writeLength = this.simulationData.transactionData.resources().footprint().readWrite().length - return (authsCount === 0) && (writeLength === 0); - } - - hasRealInvoker = async (): Promise => { - const account = await this.getAccount() - return account.accountId() !== NULL_ACCOUNT - } -} - -/** - * A transaction that has been sent to the Soroban network. This happens in two steps: - * - * 1. `sendTransaction`: initial submission of the transaction to the network. - * This step can run into problems, and will be retried with exponential - * backoff if it does. See all attempts in `sendTransactionResponseAll` and the - * most recent attempt in `sendTransactionResponse`. - * 2. `getTransaction`: once the transaction has been submitted to the network - * successfully, you need to wait for it to finalize to get the results of the - * transaction. This step can also run into problems, and will be retried with - * exponential backoff if it does. See all attempts in - * `getTransactionResponseAll` and the most recent attempt in - * `getTransactionResponse`. - */ -class SentTransaction { - public server: SorobanRpc.Server - public signed: Tx - public sendTransactionResponse?: SendTx - public sendTransactionResponseAll?: SendTx[] - public getTransactionResponse?: GetTx - public getTransactionResponseAll?: GetTx[] - - constructor(public options: AssembledTransactionOptions, public assembled: AssembledTransaction) { - this.server = new SorobanRpc.Server(this.options.rpcUrl, { - allowHttp: this.options.rpcUrl.startsWith("http://"), - }); - this.assembled = assembled - } - - static init = async ( - options: AssembledTransactionOptions, - assembled: AssembledTransaction, - secondsToWait: number = 10 - ): Promise> => { - const tx = new SentTransaction(options, assembled) - return await tx.send(secondsToWait) - } - - private send = async (secondsToWait: number = 10): Promise => { - const wallet = await this.assembled.getWallet() - - this.sendTransactionResponseAll = await withExponentialBackoff( - async (previousFailure) => { - if (previousFailure) { - // Increment transaction sequence number and resimulate before trying again - - // Soroban transaction can only have 1 operation - const op = this.assembled.raw.operations[0] as Operation.InvokeHostFunction; - - this.assembled.raw = new TransactionBuilder(await this.assembled.getAccount(), { - fee: this.assembled.raw.fee, - networkPassphrase: this.options.networkPassphrase, - }) - .setTimeout(TimeoutInfinite) - .addOperation( - Operation.invokeHostFunction({ ...op, auth: op.auth ?? [] }), - ) - .build() - - await this.assembled.simulate() - } - - const signature = await wallet.signTransaction(this.assembled.raw.toXDR(), { - networkPassphrase: this.options.networkPassphrase, - }); - - this.signed = TransactionBuilder.fromXDR( - signature, - this.options.networkPassphrase - ) as Tx - - return this.server.sendTransaction(this.signed) - }, - resp => resp.status !== "PENDING", - secondsToWait - ) - - this.sendTransactionResponse = this.sendTransactionResponseAll[this.sendTransactionResponseAll.length - 1] - - if (this.sendTransactionResponse.status !== "PENDING") { - throw new Error( - `Tried to resubmit transaction for ${secondsToWait - } seconds, but it's still failing. ` + - `All attempts: ${JSON.stringify( - this.sendTransactionResponseAll, - null, - 2 - )}` - ); - } - - const { hash } = this.sendTransactionResponse - - this.getTransactionResponseAll = await withExponentialBackoff( - () => this.server.getTransaction(hash), - resp => resp.status === SorobanRpc.Api.GetTransactionStatus.NOT_FOUND, - secondsToWait - ) - - this.getTransactionResponse = this.getTransactionResponseAll[this.getTransactionResponseAll.length - 1] - if (this.getTransactionResponse.status === SorobanRpc.Api.GetTransactionStatus.NOT_FOUND) { - console.error( - `Waited ${secondsToWait - } seconds for transaction to complete, but it did not. ` + - `Returning anyway. Check the transaction status manually. ` + - `Sent transaction: ${JSON.stringify( - this.sendTransactionResponse, - null, - 2 - )}\n` + - `All attempts to get the result: ${JSON.stringify( - this.getTransactionResponseAll, - null, - 2 - )}` - ); - } - - return this; - } - - get result(): T { - // 1. check if transaction was submitted and awaited with `getTransaction` - if ( - "getTransactionResponse" in this && - this.getTransactionResponse - ) { - // getTransactionResponse has a `returnValue` field unless it failed - if ("returnValue" in this.getTransactionResponse) { - return this.options.parseResultXdr(this.getTransactionResponse.returnValue!) - } - - // if "returnValue" not present, the transaction failed; return without parsing the result - throw new Error("Transaction failed! Cannot parse result.") - } - - // 2. otherwise, maybe it was merely sent with `sendTransaction` - if (this.sendTransactionResponse) { - const errorResult = this.sendTransactionResponse.errorResult?.result() - if (errorResult) { - throw new SendFailedError( - `Transaction simulation looked correct, but attempting to send the transaction failed. Check \`simulation\` and \`sendTransactionResponseAll\` to troubleshoot. Decoded \`sendTransactionResponse.errorResultXdr\`: ${errorResult}` - ) - } - throw new SendResultOnlyError( - `Transaction was sent to the network, but not yet awaited. No result to show. Await transaction completion with \`getTransaction(sendTransactionResponse.hash)\`` - ) - } - - // 3. finally, if neither of those are present, throw an error - throw new Error(`Sending transaction failed: ${JSON.stringify(this.assembled)}`) - } -} - -/** - * Keep calling a `fn` for `secondsToWait` seconds, if `keepWaitingIf` is true. - * Returns an array of all attempts to call the function. - */ -async function withExponentialBackoff( - fn: (previousFailure?: T) => Promise, - keepWaitingIf: (result: T) => boolean, - secondsToWait: number, - exponentialFactor = 1.5, - verbose = false, -): Promise { - const attempts: T[] = [] - - let count = 0 - attempts.push(await fn()) - if (!keepWaitingIf(attempts[attempts.length - 1])) return attempts - - const waitUntil = new Date(Date.now() + secondsToWait * 1000).valueOf() - let waitTime = 1000 - let totalWaitTime = waitTime - - while (Date.now() < waitUntil && keepWaitingIf(attempts[attempts.length - 1])) { - count++ - // Wait a beat - if (verbose) { - console.info(`Waiting ${waitTime}ms before trying again (bringing the total wait time to ${totalWaitTime}ms so far, of total ${secondsToWait * 1000}ms)`) - } - await new Promise(res => setTimeout(res, waitTime)) - // Exponential backoff - waitTime = waitTime * exponentialFactor; - if (new Date(Date.now() + waitTime).valueOf() > waitUntil) { - waitTime = waitUntil - Date.now() - if (verbose) { - console.info(`was gonna wait too long; new waitTime: ${waitTime}ms`) - } - } - totalWaitTime = waitTime + totalWaitTime - // Try again - attempts.push(await fn(attempts[attempts.length - 1])) - if (verbose && keepWaitingIf(attempts[attempts.length - 1])) { - console.info( - `${count}. Called ${fn}; ${attempts.length - } prev attempts. Most recent: ${JSON.stringify(attempts[attempts.length - 1], null, 2) - }` - ) - } - } - - return attempts -} diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/src/index.ts b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/src/index.ts index e31192254d..9fd5e51f94 100644 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/src/index.ts +++ b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/src/index.ts @@ -1,6 +1,10 @@ import { ContractSpec, Address } from '@stellar/stellar-sdk'; import { Buffer } from "buffer"; -import { AssembledTransaction, Ok, Err } from './assembled-tx.js'; +import { + AssembledTransaction, + ContractClient, + ContractClientOptions, +} from '@stellar/stellar-sdk/lib/contract_client/index.js'; import type { u32, i32, @@ -13,13 +17,11 @@ import type { Option, Typepoint, Duration, - Error_, - Result, -} from './assembled-tx.js'; -import type { ClassOptions, XDR_BASE64 } from './method-options.js'; - -export * from './assembled-tx.js'; -export * from './method-options.js'; +} from '@stellar/stellar-sdk/lib/contract_client'; +import { Result } from '@stellar/stellar-sdk/lib/rust_types/index.js'; +export * from '@stellar/stellar-sdk' +export * from '@stellar/stellar-sdk/lib/contract_client/index.js' +export * from '@stellar/stellar-sdk/lib/rust_types/index.js' if (typeof window !== 'undefined') { //@ts-ignore Buffer exists @@ -28,65 +30,606 @@ if (typeof window !== 'undefined') { export const networks = { - futurenet: { - networkPassphrase: "Test SDF Future Network ; October 2022", - contractId: "CBYMYMSDF6FBDNCFJCRC7KMO4REYFPOH2U4N7FXI3GJO6YXNCQ43CDSK", - } + futurenet: { + networkPassphrase: "Test SDF Future Network ; October 2022", + contractId: "CBYMYMSDF6FBDNCFJCRC7KMO4REYFPOH2U4N7FXI3GJO6YXNCQ43CDSK", + } } as const + /** - This is from the rust doc above the struct Test - */ + * This is from the rust doc above the struct Test + */ export interface Test { - /** - - */ -a: u32; - /** - - */ -b: boolean; - /** - - */ -c: string; + a: u32; + b: boolean; + c: string; } -/** - - */ export type SimpleEnum = {tag: "First", values: void} | {tag: "Second", values: void} | {tag: "Third", values: void}; -/** - - */ export enum RoyalCard { Jack = 11, Queen = 12, King = 13, } -/** - - */ export type TupleStruct = readonly [Test, SimpleEnum]; -/** - - */ export type ComplexEnum = {tag: "Struct", values: readonly [Test]} | {tag: "Tuple", values: readonly [TupleStruct]} | {tag: "Enum", values: readonly [SimpleEnum]} | {tag: "Asset", values: readonly [string, i128]} | {tag: "Void", values: void}; -/** - - */ export const Errors = { -1: {message:"Please provide an odd number"} + 1: {message:"Please provide an odd number"} } -export class Contract { - spec: ContractSpec; - constructor(public readonly options: ClassOptions) { - this.spec = new ContractSpec([ - "AAAAAQAAAC9UaGlzIGlzIGZyb20gdGhlIHJ1c3QgZG9jIGFib3ZlIHRoZSBzdHJ1Y3QgVGVzdAAAAAAAAAAABFRlc3QAAAADAAAAAAAAAAFhAAAAAAAABAAAAAAAAAABYgAAAAAAAAEAAAAAAAAAAWMAAAAAAAAR", +export interface Client { + /** + * Construct and simulate a hello transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + hello: ({hello}: {hello: string}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a woid transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + woid: (options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a val transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + val: (options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a u32_fail_on_even transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + u32FailOnEven: ({u32_}: {u32_: u32}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>> + + /** + * Construct and simulate a u32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + u32: ({u32_}: {u32_: u32}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a i32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + i32: ({i32_}: {i32_: i32}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a i64_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + i64: ({i64_}: {i64_: i64}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a strukt_hel transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. * + * Example contract method which takes a struct + */ + struktHel: ({strukt}: {strukt: Test}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>> + + /** + * Construct and simulate a strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + strukt: ({strukt}: {strukt: Test}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a simple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + simple: ({simple}: {simple: SimpleEnum}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a complex transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + complex: ({complex}: {complex: ComplexEnum}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a addresse transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + addresse: ({addresse}: {addresse: string}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a bytes transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + bytes: ({bytes}: {bytes: Buffer}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a bytes_n transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + bytesN: ({bytes_n}: {bytes_n: Buffer}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a card transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + card: ({card}: {card: RoyalCard}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a boolean transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + boolean: ({boolean}: {boolean: boolean}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a not transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. * + * Negates a boolean value + */ + not: ({boolean}: {boolean: boolean}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a i128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + i128: ({i128}: {i128: i128}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a u128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + u128: ({u128}: {u128: u128}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a multi_args transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + multiArgs: ({a, b}: {a: u32, b: boolean}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a map transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + map: ({map}: {map: Map}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>> + + /** + * Construct and simulate a vec transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + vec: ({vec}: {vec: Array}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>> + + /** + * Construct and simulate a tuple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + tuple: ({tuple}: {tuple: readonly [string, u32]}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a option transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. * + * Example of an optional argument + */ + option: ({option}: {option: Option}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise>> + + /** + * Construct and simulate a u256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + u256: ({u256}: {u256: u256}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a i256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + i256: ({i256}: {i256: i256}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a string transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + string: ({string}: {string: string}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + + /** + * Construct and simulate a tuple_strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. + */ + tupleStrukt: ({tuple_strukt}: {tuple_strukt: TupleStruct}, options?: { + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }) => Promise> + +} +export class Client extends ContractClient { + constructor(public readonly options: ContractClientOptions) { + super( + new ContractSpec([ "AAAAAQAAAC9UaGlzIGlzIGZyb20gdGhlIHJ1c3QgZG9jIGFib3ZlIHRoZSBzdHJ1Y3QgVGVzdAAAAAAAAAAABFRlc3QAAAADAAAAAAAAAAFhAAAAAAAABAAAAAAAAAABYgAAAAAAAAEAAAAAAAAAAWMAAAAAAAAR", "AAAAAgAAAAAAAAAAAAAAClNpbXBsZUVudW0AAAAAAAMAAAAAAAAAAAAAAAVGaXJzdAAAAAAAAAAAAAAAAAAABlNlY29uZAAAAAAAAAAAAAAAAAAFVGhpcmQAAAA=", "AAAAAwAAAAAAAAAAAAAACVJveWFsQ2FyZAAAAAAAAAMAAAAAAAAABEphY2sAAAALAAAAAAAAAAVRdWVlbgAAAAAAAAwAAAAAAAAABEtpbmcAAAAN", "AAAAAQAAAAAAAAAAAAAAC1R1cGxlU3RydWN0AAAAAAIAAAAAAAAAATAAAAAAAAfQAAAABFRlc3QAAAAAAAAAATEAAAAAAAfQAAAAClNpbXBsZUVudW0AAA==", @@ -119,640 +662,38 @@ export class Contract { "AAAAAAAAAAAAAAAEdTI1NgAAAAEAAAAAAAAABHUyNTYAAAAMAAAAAQAAAAw=", "AAAAAAAAAAAAAAAEaTI1NgAAAAEAAAAAAAAABGkyNTYAAAANAAAAAQAAAA0=", "AAAAAAAAAAAAAAAGc3RyaW5nAAAAAAABAAAAAAAAAAZzdHJpbmcAAAAAABAAAAABAAAAEA==", - "AAAAAAAAAAAAAAAMdHVwbGVfc3RydWt0AAAAAQAAAAAAAAAMdHVwbGVfc3RydWt0AAAH0AAAAAtUdXBsZVN0cnVjdAAAAAABAAAH0AAAAAtUdXBsZVN0cnVjdAA=" - ]); - } - private readonly parsers = { - hello: (result: XDR_BASE64): string => this.spec.funcResToNative("hello", result), - woid: () => {}, - val: (result: XDR_BASE64): any => this.spec.funcResToNative("val", result), - u32FailOnEven: (result: XDR_BASE64 | Err): Ok | Err => { - if (result instanceof Err) return result - return new Ok(this.spec.funcResToNative("u32_fail_on_even", result)) - }, - u32: (result: XDR_BASE64): u32 => this.spec.funcResToNative("u32_", result), - i32: (result: XDR_BASE64): i32 => this.spec.funcResToNative("i32_", result), - i64: (result: XDR_BASE64): i64 => this.spec.funcResToNative("i64_", result), - struktHel: (result: XDR_BASE64): Array => this.spec.funcResToNative("strukt_hel", result), - strukt: (result: XDR_BASE64): Test => this.spec.funcResToNative("strukt", result), - simple: (result: XDR_BASE64): SimpleEnum => this.spec.funcResToNative("simple", result), - complex: (result: XDR_BASE64): ComplexEnum => this.spec.funcResToNative("complex", result), - addresse: (result: XDR_BASE64): string => this.spec.funcResToNative("addresse", result), - bytes: (result: XDR_BASE64): Buffer => this.spec.funcResToNative("bytes", result), - bytesN: (result: XDR_BASE64): Buffer => this.spec.funcResToNative("bytes_n", result), - card: (result: XDR_BASE64): RoyalCard => this.spec.funcResToNative("card", result), - boolean: (result: XDR_BASE64): boolean => this.spec.funcResToNative("boolean", result), - not: (result: XDR_BASE64): boolean => this.spec.funcResToNative("not", result), - i128: (result: XDR_BASE64): i128 => this.spec.funcResToNative("i128", result), - u128: (result: XDR_BASE64): u128 => this.spec.funcResToNative("u128", result), - multiArgs: (result: XDR_BASE64): u32 => this.spec.funcResToNative("multi_args", result), - map: (result: XDR_BASE64): Map => this.spec.funcResToNative("map", result), - vec: (result: XDR_BASE64): Array => this.spec.funcResToNative("vec", result), - tuple: (result: XDR_BASE64): readonly [string, u32] => this.spec.funcResToNative("tuple", result), - option: (result: XDR_BASE64): Option => this.spec.funcResToNative("option", result), - u256: (result: XDR_BASE64): u256 => this.spec.funcResToNative("u256", result), - i256: (result: XDR_BASE64): i256 => this.spec.funcResToNative("i256", result), - string: (result: XDR_BASE64): string => this.spec.funcResToNative("string", result), - tupleStrukt: (result: XDR_BASE64): TupleStruct => this.spec.funcResToNative("tuple_strukt", result) - }; - private txFromJSON = (json: string): AssembledTransaction => { - const { method, ...tx } = JSON.parse(json) - return AssembledTransaction.fromJSON( - { - ...this.options, - method, - parseResultXdr: this.parsers[method], - }, - tx, - ); - } - public readonly fromJSON = { - hello: this.txFromJSON>, - woid: this.txFromJSON>, - val: this.txFromJSON>, - u32FailOnEven: this.txFromJSON>, - u32: this.txFromJSON>, - i32: this.txFromJSON>, - i64: this.txFromJSON>, - struktHel: this.txFromJSON>, - strukt: this.txFromJSON>, - simple: this.txFromJSON>, - complex: this.txFromJSON>, - addresse: this.txFromJSON>, - bytes: this.txFromJSON>, - bytesN: this.txFromJSON>, - card: this.txFromJSON>, - boolean: this.txFromJSON>, - not: this.txFromJSON>, - i128: this.txFromJSON>, - u128: this.txFromJSON>, - multiArgs: this.txFromJSON>, - map: this.txFromJSON>, - vec: this.txFromJSON>, - tuple: this.txFromJSON>, - option: this.txFromJSON>, - u256: this.txFromJSON>, - i256: this.txFromJSON>, - string: this.txFromJSON>, - tupleStrukt: this.txFromJSON> - } - /** - * Construct and simulate a hello transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - hello = async ({hello}: {hello: string}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'hello', - args: this.spec.funcArgsToScVals("hello", {hello}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['hello'], - }); - } - - - /** - * Construct and simulate a woid transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - woid = async (options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'woid', - args: this.spec.funcArgsToScVals("woid", {}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['woid'], - }); - } - - - /** - * Construct and simulate a val transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - val = async (options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'val', - args: this.spec.funcArgsToScVals("val", {}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['val'], - }); - } - - - /** - * Construct and simulate a u32_fail_on_even transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - u32FailOnEven = async ({u32_}: {u32_: u32}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'u32_fail_on_even', - args: this.spec.funcArgsToScVals("u32_fail_on_even", {u32_}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['u32FailOnEven'], - }); - } - - - /** - * Construct and simulate a u32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - u32 = async ({u32_}: {u32_: u32}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'u32_', - args: this.spec.funcArgsToScVals("u32_", {u32_}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['u32'], - }); - } - - - /** - * Construct and simulate a i32_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - i32 = async ({i32_}: {i32_: i32}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'i32_', - args: this.spec.funcArgsToScVals("i32_", {i32_}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['i32'], - }); - } - - - /** - * Construct and simulate a i64_ transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - i64 = async ({i64_}: {i64_: i64}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'i64_', - args: this.spec.funcArgsToScVals("i64_", {i64_}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['i64'], - }); - } - - - /** - * Construct and simulate a strukt_hel transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Example contract method which takes a struct - */ - struktHel = async ({strukt}: {strukt: Test}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'strukt_hel', - args: this.spec.funcArgsToScVals("strukt_hel", {strukt}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['struktHel'], - }); - } - - - /** - * Construct and simulate a strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - strukt = async ({strukt}: {strukt: Test}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'strukt', - args: this.spec.funcArgsToScVals("strukt", {strukt}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['strukt'], - }); - } - - - /** - * Construct and simulate a simple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - simple = async ({simple}: {simple: SimpleEnum}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'simple', - args: this.spec.funcArgsToScVals("simple", {simple}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['simple'], - }); - } - - - /** - * Construct and simulate a complex transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - complex = async ({complex}: {complex: ComplexEnum}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'complex', - args: this.spec.funcArgsToScVals("complex", {complex}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['complex'], - }); - } - - - /** - * Construct and simulate a addresse transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - addresse = async ({addresse}: {addresse: string}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'addresse', - args: this.spec.funcArgsToScVals("addresse", {addresse: new Address(addresse)}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['addresse'], - }); - } - - - /** - * Construct and simulate a bytes transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - bytes = async ({bytes}: {bytes: Buffer}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'bytes', - args: this.spec.funcArgsToScVals("bytes", {bytes}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['bytes'], - }); - } - - - /** - * Construct and simulate a bytes_n transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - bytesN = async ({bytes_n}: {bytes_n: Buffer}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'bytes_n', - args: this.spec.funcArgsToScVals("bytes_n", {bytes_n}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['bytesN'], - }); - } - - - /** - * Construct and simulate a card transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - card = async ({card}: {card: RoyalCard}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'card', - args: this.spec.funcArgsToScVals("card", {card}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['card'], - }); - } - - - /** - * Construct and simulate a boolean transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - boolean = async ({boolean}: {boolean: boolean}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'boolean', - args: this.spec.funcArgsToScVals("boolean", {boolean}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['boolean'], - }); - } - - - /** - * Construct and simulate a not transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Negates a boolean value - */ - not = async ({boolean}: {boolean: boolean}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'not', - args: this.spec.funcArgsToScVals("not", {boolean}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['not'], - }); - } - - - /** - * Construct and simulate a i128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - i128 = async ({i128}: {i128: i128}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'i128', - args: this.spec.funcArgsToScVals("i128", {i128}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['i128'], - }); - } - - - /** - * Construct and simulate a u128 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - u128 = async ({u128}: {u128: u128}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'u128', - args: this.spec.funcArgsToScVals("u128", {u128}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['u128'], - }); - } - - - /** - * Construct and simulate a multi_args transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - multiArgs = async ({a, b}: {a: u32, b: boolean}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'multi_args', - args: this.spec.funcArgsToScVals("multi_args", {a, b}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['multiArgs'], - }); - } - - - /** - * Construct and simulate a map transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - map = async ({map}: {map: Map}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'map', - args: this.spec.funcArgsToScVals("map", {map}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['map'], - }); - } - - - /** - * Construct and simulate a vec transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - vec = async ({vec}: {vec: Array}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'vec', - args: this.spec.funcArgsToScVals("vec", {vec}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['vec'], - }); - } - - - /** - * Construct and simulate a tuple transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - tuple = async ({tuple}: {tuple: readonly [string, u32]}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'tuple', - args: this.spec.funcArgsToScVals("tuple", {tuple}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['tuple'], - }); - } - - - /** - * Construct and simulate a option transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.Example of an optional argument - */ - option = async ({option}: {option: Option}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'option', - args: this.spec.funcArgsToScVals("option", {option}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['option'], - }); - } - - - /** - * Construct and simulate a u256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - u256 = async ({u256}: {u256: u256}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'u256', - args: this.spec.funcArgsToScVals("u256", {u256}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['u256'], - }); - } - - - /** - * Construct and simulate a i256 transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - i256 = async ({i256}: {i256: i256}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'i256', - args: this.spec.funcArgsToScVals("i256", {i256}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['i256'], - }); - } - - - /** - * Construct and simulate a string transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - string = async ({string}: {string: string}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'string', - args: this.spec.funcArgsToScVals("string", {string}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['string'], - }); - } - - - /** - * Construct and simulate a tuple_strukt transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object. - */ - tupleStrukt = async ({tuple_strukt}: {tuple_strukt: TupleStruct}, options: { - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - } = {}) => { - return await AssembledTransaction.fromSimulation({ - method: 'tuple_strukt', - args: this.spec.funcArgsToScVals("tuple_strukt", {tuple_strukt}), - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['tupleStrukt'], - }); - } - + "AAAAAAAAAAAAAAAMdHVwbGVfc3RydWt0AAAAAQAAAAAAAAAMdHVwbGVfc3RydWt0AAAH0AAAAAtUdXBsZVN0cnVjdAAAAAABAAAH0AAAAAtUdXBsZVN0cnVjdAA=" ]), + options + ) + } + public readonly fromJSON = { + hello: this.txFromJSON, + woid: this.txFromJSON, + val: this.txFromJSON, + u32FailOnEven: this.txFromJSON>, + u32: this.txFromJSON, + i32: this.txFromJSON, + i64: this.txFromJSON, + struktHel: this.txFromJSON>, + strukt: this.txFromJSON, + simple: this.txFromJSON, + complex: this.txFromJSON, + addresse: this.txFromJSON, + bytes: this.txFromJSON, + bytesN: this.txFromJSON, + card: this.txFromJSON, + boolean: this.txFromJSON, + not: this.txFromJSON, + i128: this.txFromJSON, + u128: this.txFromJSON, + multiArgs: this.txFromJSON, + map: this.txFromJSON>, + vec: this.txFromJSON>, + tuple: this.txFromJSON, + option: this.txFromJSON>, + u256: this.txFromJSON, + i256: this.txFromJSON, + string: this.txFromJSON, + tupleStrukt: this.txFromJSON + } } \ No newline at end of file diff --git a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/src/method-options.ts b/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/src/method-options.ts deleted file mode 100644 index 737ae0a050..0000000000 --- a/cmd/crates/soroban-spec-typescript/fixtures/test_custom_types/src/method-options.ts +++ /dev/null @@ -1,50 +0,0 @@ -// defined this way so typeahead shows full union, not named alias -let responseTypes: 'simulated' | 'full' | undefined -export type ResponseTypes = typeof responseTypes - -export type XDR_BASE64 = string - -export interface Wallet { - isConnected: () => Promise, - isAllowed: () => Promise, - getUserInfo: () => Promise<{ publicKey?: string }>, - signTransaction: (tx: XDR_BASE64, opts?: { - network?: string, - networkPassphrase?: string, - accountToSign?: string, - }) => Promise, - signAuthEntry: ( - entryXdr: XDR_BASE64, - opts?: { - accountToSign?: string; - } - ) => Promise -} - -export type ClassOptions = { - contractId: string - networkPassphrase: string - rpcUrl: string - errorTypes?: Record - /** - * A Wallet interface, such as Freighter, that has the methods `isConnected`, `isAllowed`, `getUserInfo`, and `signTransaction`. If not provided, will attempt to import and use Freighter. Example: - * - * @example - * ```ts - * import freighter from "@stellar/freighter-api"; - * import { Contract } from "test_custom_types"; - * const contract = new Contract({ - * …, - * wallet: freighter, - * }) - * ``` - */ - wallet?: Wallet -} - -export type MethodOptions = { - /** - * The fee to pay for the transaction. Default: soroban-sdk's BASE_FEE ('100') - */ - fee?: number -} diff --git a/cmd/crates/soroban-spec-typescript/src/boilerplate.rs b/cmd/crates/soroban-spec-typescript/src/boilerplate.rs index 7ffe641896..0d250d4cf2 100644 --- a/cmd/crates/soroban-spec-typescript/src/boilerplate.rs +++ b/cmd/crates/soroban-spec-typescript/src/boilerplate.rs @@ -78,22 +78,16 @@ impl Project { ("INSERT_RPC_URL_HERE", rpc_url), ]; let root: &Path = self.as_ref(); - [ - "package.json", - "README.md", - "src/assembled-tx.ts", - "src/index.ts", - "src/method-options.ts", - ] - .into_iter() - .try_for_each(|file_name| { - let file = &root.join(file_name); - let mut contents = fs::read_to_string(file).unwrap(); - for (pattern, replacement) in replacement_strings { - contents = contents.replace(pattern, replacement); - } - fs::write(file, contents) - }) + ["package.json", "README.md", "src/index.ts"] + .into_iter() + .try_for_each(|file_name| { + let file = &root.join(file_name); + let mut contents = fs::read_to_string(file).unwrap(); + for (pattern, replacement) in replacement_strings { + contents = contents.replace(pattern, replacement); + } + fs::write(file, contents) + }) } fn append_index_ts( @@ -119,10 +113,10 @@ impl Project { }; format!( r#"export const networks = {{ - {network}: {{ - networkPassphrase: "{network_passphrase}", - contractId: "{contract_id}", - }} + {network}: {{ + networkPassphrase: "{network_passphrase}", + contractId: "{contract_id}", + }} }} as const"# ) } diff --git a/cmd/crates/soroban-spec-typescript/src/lib.rs b/cmd/crates/soroban-spec-typescript/src/lib.rs index 790f43b071..f80aa55e79 100644 --- a/cmd/crates/soroban-spec-typescript/src/lib.rs +++ b/cmd/crates/soroban-spec-typescript/src/lib.rs @@ -61,49 +61,29 @@ pub fn generate_from_wasm(wasm: &[u8]) -> Result { } fn generate_class(fns: &[Entry], spec: &[ScSpecEntry]) -> String { - let methods = fns.iter().map(entry_to_method).join("\n\n "); - let parsers = fns - .iter() - .filter_map(entry_to_parser) - .map(|(method, parser)| format!("{method}: {parser}")) - .join(",\n "); + let method_types = fns.iter().map(entry_to_method_type).join(""); let from_jsons = fns .iter() - .filter_map(entry_to_parser) - .map(|(method, _)| { - format!("{method}: this.txFromJSON>") - }) + .filter_map(entry_to_name_and_return_type) + .map(|(method, return_type)| format!("{method}: this.txFromJSON<{return_type}>")) .join(",\n "); let spec = spec .iter() .map(|s| format!("\"{}\"", s.to_xdr_base64(Limits::none()).unwrap())) .join(",\n "); format!( - r#"export class Contract {{ - spec: ContractSpec; - constructor(public readonly options: ClassOptions) {{ - this.spec = new ContractSpec([ - {spec} - ]); - }} - private readonly parsers = {{ - {parsers} - }}; - private txFromJSON = (json: string): AssembledTransaction => {{ - const {{ method, ...tx }} = JSON.parse(json) - return AssembledTransaction.fromJSON( - {{ - ...this.options, - method, - parseResultXdr: this.parsers[method], - }}, - tx, - ); - }} - public readonly fromJSON = {{ - {from_jsons} - }} - {methods} + r#"export interface Client {{{method_types} +}} +export class Client extends ContractClient {{ + constructor(public readonly options: ContractClientOptions) {{ + super( + new ContractSpec([ {spec} ]), + options + ) + }} + public readonly fromJSON = {{ + {from_jsons} + }} }}"#, ) } @@ -120,27 +100,35 @@ pub fn generate(spec: &[ScSpecEntry]) -> String { let (fns, other): (Vec<_>, Vec<_>) = collected .into_iter() .partition(|entry| matches!(entry, Entry::Function { .. })); - let top = other.iter().map(entry_to_method).join("\n"); + let top = other.iter().map(entry_to_method_type).join("\n"); let bottom = generate_class(&fns, spec); format!("{top}\n\n{bottom}") } fn doc_to_ts_doc(doc: &str, method: Option<&str>) -> String { - let header = if let Some(method) = method { - format!( + if method.is_none() { + if doc.is_empty() { + return String::new(); + } + let doc = doc.split('\n').join("\n * "); + return format!( r#"/** - * Construct and simulate a {method} transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object."# - ) - } else { - "/**\n ".to_string() - }; - let footer = "\n */\n"; - let body = if doc.is_empty() { + * {doc} + */ +"# + ); + } + let method = method.unwrap(); + let doc = if doc.is_empty() { String::new() } else { - doc.split('\n').join("\n * ") + format!(" *\n * {}", doc.split('\n').join("\n * ")) }; - format!(r#"{header}{body}{footer}"#) + format!( + r#"/** + * Construct and simulate a {method} transaction. Returns an `AssembledTransaction` object which will have a `result` field containing the result of the simulation. If this transaction changes contract state, you will need to call `signAndSend()` on the returned object.{doc} + */"# + ) } fn is_error_enum(entry: &ScSpecEntry) -> bool { @@ -148,67 +136,50 @@ fn is_error_enum(entry: &ScSpecEntry) -> bool { } const METHOD_OPTIONS: &str = r"{ - /** - * The fee to pay for the transaction. Default: 100. - */ - fee?: number, - }"; + /** + * The fee to pay for the transaction. Default: BASE_FEE + */ + fee?: number; + + /** + * The maximum amount of time to wait for the transaction to complete. Default: DEFAULT_TIMEOUT + */ + timeoutInSeconds?: number; + + /** + * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true + */ + simulate?: boolean; + }"; fn jsify_name(name: &String) -> String { name.to_lower_camel_case() } -pub fn entry_to_parser(entry: &Entry) -> Option<(String, String)> { +pub fn entry_to_name_and_return_type(entry: &Entry) -> Option<(String, String)> { if let Entry::Function { name, outputs, .. } = entry { - let mut is_result = false; - let mut return_type: String; - if outputs.is_empty() { - return_type = "void".to_owned(); - } else if outputs.len() == 1 { - return_type = type_to_ts(&outputs[0]); - is_result = return_type.starts_with("Result<"); - } else { - return_type = format!("readonly [{}]", outputs.iter().map(type_to_ts).join(", ")); - }; - - if is_result { - return_type = return_type - .strip_prefix("Result<") - .unwrap() - .strip_suffix('>') - .unwrap() - .to_owned(); - return_type = format!("Ok<{return_type}> | Err"); - } - - let output = outputs - .first() - .map(|_| format!("this.spec.funcResToNative(\"{name}\", result)")) - .unwrap_or_default(); - let parse_result_xdr = if return_type == "void" { - r"() => {}".to_owned() - } else if is_result { - format!( - r"(result: XDR_BASE64 | Err): {return_type} => {{ - if (result instanceof Err) return result - return new Ok({output}) - }}" - ) - } else { - format!(r"(result: XDR_BASE64): {return_type} => {output}") - }; - let js_name = jsify_name(name); - Some((js_name, parse_result_xdr)) + Some((jsify_name(name), outputs_to_return_type(outputs))) } else { None } } +pub fn outputs_to_return_type(outputs: &[Type]) -> String { + match outputs { + [] => "null".to_owned(), + [output] => type_to_ts(output), + outputs => format!("readonly [{}]", outputs.iter().map(type_to_ts).join(", ")), + } +} #[allow(clippy::too_many_lines)] -pub fn entry_to_method(entry: &Entry) -> String { +pub fn entry_to_method_type(entry: &Entry) -> String { match entry { Entry::Function { - doc, name, inputs, .. + doc, + name, + inputs, + outputs, + .. } => { let input_vals = inputs.iter().map(func_input_to_arg_name).join(", "); let input = (!inputs.is_empty()) @@ -219,33 +190,23 @@ pub fn entry_to_method(entry: &Entry) -> String { ) }) .unwrap_or_default(); - let ts_doc = doc_to_ts_doc(doc, Some(name)); - let (js_name, _) = entry_to_parser(entry).unwrap(); - let parsed_scvals = inputs.iter().map(parse_arg_to_scval).join(", "); - let args = - format!("args: this.spec.funcArgsToScVals(\"{name}\", {{{parsed_scvals}}}),"); - let body = format!( - r#"return await AssembledTransaction.fromSimulation({{ - method: '{name}', - {args} - ...options, - ...this.options, - errorTypes: Errors, - parseResultXdr: this.parsers['{js_name}'], - }});"# - ); + let doc = doc_to_ts_doc(doc, Some(name)); + let js_name = jsify_name(name); + let return_type = outputs_to_return_type(outputs); format!( - r#" {ts_doc} {js_name} = async ({input}options: {METHOD_OPTIONS} = {{}}) => {{ - {body} - }} + r#" + {doc} + {js_name}: ({input}options?: {METHOD_OPTIONS}) => Promise> "# ) } + Entry::Struct { doc, name, fields } => { let docs = doc_to_ts_doc(doc, None); let fields = fields.iter().map(field_to_ts).join("\n "); format!( - r#"{docs}export interface {name} {{ + r#" +{docs}export interface {name} {{ {fields} }} "# @@ -288,7 +249,7 @@ pub fn entry_to_method(entry: &Entry) -> String { .join(",\n "); format!( r#"{doc}export const Errors = {{ -{cases} + {cases} }}"# ) } diff --git a/cmd/crates/soroban-spec-typescript/src/project_template/package.json b/cmd/crates/soroban-spec-typescript/src/project_template/package.json index 40a610e0e2..1fd6a6718e 100644 --- a/cmd/crates/soroban-spec-typescript/src/project_template/package.json +++ b/cmd/crates/soroban-spec-typescript/src/project_template/package.json @@ -4,7 +4,7 @@ "dependencies": { "@stellar/freighter-api": "2.0.0", "buffer": "6.0.3", - "@stellar/stellar-sdk": "11.2.2" + "@stellar/stellar-sdk": "stellar/js-stellar-sdk#bindings" }, "scripts": { "build": "node ./scripts/build.mjs" diff --git a/cmd/crates/soroban-spec-typescript/src/project_template/src/assembled-tx.ts b/cmd/crates/soroban-spec-typescript/src/project_template/src/assembled-tx.ts deleted file mode 100644 index f4f892d4d3..0000000000 --- a/cmd/crates/soroban-spec-typescript/src/project_template/src/assembled-tx.ts +++ /dev/null @@ -1,664 +0,0 @@ -import { - Account, - Address, - Contract, - Operation, - SorobanRpc, - StrKey, - TimeoutInfinite, - TransactionBuilder, - authorizeEntry, - hash, - nativeToScVal, - xdr, - BASE_FEE, -} from "@stellar/stellar-sdk"; -import type { Memo, MemoType, Transaction } from "@stellar/stellar-sdk"; -import { Buffer } from "buffer"; -import type { - ClassOptions, - MethodOptions, - Wallet, - XDR_BASE64, -} from "./method-options.js"; - -export type Tx = Transaction, Operation[]> - -export class ExpiredStateError extends Error { } -export class NeedsMoreSignaturesError extends Error { } -export class WalletDisconnectedError extends Error { } -export class SendResultOnlyError extends Error { } -export class SendFailedError extends Error { } -export class NoUnsignedNonInvokerAuthEntriesError extends Error { } - -type SendTx = SorobanRpc.Api.SendTransactionResponse; -type GetTx = SorobanRpc.Api.GetTransactionResponse; - -export type u32 = number; -export type i32 = number; -export type u64 = bigint; -export type i64 = bigint; -export type u128 = bigint; -export type i128 = bigint; -export type u256 = bigint; -export type i256 = bigint; -export type Option = T | undefined; -export type Typepoint = bigint; -export type Duration = bigint; -export {Address}; - -/// Error interface containing the error message -export interface Error_ { message: string }; - -export interface Result { - unwrap(): T, - unwrapErr(): E, - isOk(): boolean, - isErr(): boolean, -}; - -export class Ok implements Result { - constructor(readonly value: T) { } - unwrapErr(): E { - throw new Error('No error'); - } - unwrap(): T { - return this.value; - } - - isOk(): boolean { - return true; - } - - isErr(): boolean { - return !this.isOk() - } -} - -export class Err implements Result { - constructor(readonly error: E) { } - unwrapErr(): E { - return this.error; - } - unwrap(): never { - throw new Error(this.error.message); - } - - isOk(): boolean { - return false; - } - - isErr(): boolean { - return !this.isOk() - } -} - -export const contractErrorPattern = /Error\(Contract, #(\d+)\)/; - -type AssembledTransactionOptions = MethodOptions & - ClassOptions & { - method: string; - args?: any[]; - parseResultXdr: (xdr: string | xdr.ScVal | Err) => T; - }; - -export const NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF" - -export class AssembledTransaction { - public raw: Tx - private simulation?: SorobanRpc.Api.SimulateTransactionResponse - private simulationResult?: SorobanRpc.Api.SimulateHostFunctionResult - private simulationTransactionData?: xdr.SorobanTransactionData - private server: SorobanRpc.Server - - toJSON() { - return JSON.stringify({ - method: this.options.method, - tx: this.raw?.toXDR(), - simulationResult: { - auth: this.simulationData.result.auth.map(a => a.toXDR('base64')), - retval: this.simulationData.result.retval.toXDR('base64'), - }, - simulationTransactionData: this.simulationData.transactionData.toXDR('base64'), - }) - } - - static fromJSON( - options: Omit, 'args'>, - { tx, simulationResult, simulationTransactionData }: - { - tx: XDR_BASE64, - simulationResult: { - auth: XDR_BASE64[], - retval: XDR_BASE64, - }, - simulationTransactionData: XDR_BASE64, - } - ): AssembledTransaction { - const txn = new AssembledTransaction(options) - txn.raw = TransactionBuilder.fromXDR(tx, options.networkPassphrase) as Tx - txn.simulationResult = { - auth: simulationResult.auth.map(a => xdr.SorobanAuthorizationEntry.fromXDR(a, 'base64')), - retval: xdr.ScVal.fromXDR(simulationResult.retval, 'base64'), - } - txn.simulationTransactionData = xdr.SorobanTransactionData.fromXDR(simulationTransactionData, 'base64') - return txn - } - - private constructor(public options: AssembledTransactionOptions) { - this.server = new SorobanRpc.Server(this.options.rpcUrl, { - allowHttp: this.options.rpcUrl.startsWith("http://"), - }); - } - - static async fromSimulation(options: AssembledTransactionOptions): Promise> { - const tx = new AssembledTransaction(options) - const contract = new Contract(options.contractId); - - tx.raw = new TransactionBuilder(await tx.getAccount(), { - fee: options.fee?.toString(10) ?? BASE_FEE, - networkPassphrase: options.networkPassphrase, - }) - .addOperation(contract.call(options.method, ...(options.args ?? []))) - .setTimeout(TimeoutInfinite) - .build(); - - return await tx.simulate() - } - - simulate = async (): Promise => { - if (!this.raw) throw new Error('Transaction has not yet been assembled') - this.simulation = await this.server.simulateTransaction(this.raw); - - if (SorobanRpc.Api.isSimulationSuccess(this.simulation)) { - this.raw = SorobanRpc.assembleTransaction( - this.raw, - this.simulation - ).build() - } - - return this - } - - get simulationData(): { - result: SorobanRpc.Api.SimulateHostFunctionResult - transactionData: xdr.SorobanTransactionData - } { - if (this.simulationResult && this.simulationTransactionData) { - return { - result: this.simulationResult, - transactionData: this.simulationTransactionData, - } - } - // else, we know we just did the simulation on this machine - const simulation = this.simulation! - if (SorobanRpc.Api.isSimulationError(simulation)) { - throw new Error(`Transaction simulation failed: "${simulation.error}"`) - } - - if (SorobanRpc.Api.isSimulationRestore(simulation)) { - throw new ExpiredStateError(`You need to restore some contract state before you can invoke this method. ${JSON.stringify(simulation, null, 2)}`) - } - - if (!simulation.result) { - throw new Error(`Expected an invocation simulation, but got no 'result' field. Simulation: ${JSON.stringify(simulation, null, 2)}`) - } - - // add to object for serialization & deserialization - this.simulationResult = simulation.result - this.simulationTransactionData = simulation.transactionData.build() - - return { - result: this.simulationResult, - transactionData: this.simulationTransactionData!, - } - } - - get result(): T { - try { - return this.options.parseResultXdr(this.simulationData.result.retval) - } catch (e) { - let err = this.parseError(e.toString()) - if (err) return err as T - throw e - } - } - - parseError(errorMessage: string): Err | undefined { - if (!this.options.errorTypes) return - const match = errorMessage.match(contractErrorPattern) - if (!match) return - let i = parseInt(match[1], 10) - let err = this.options.errorTypes[i] - if (err) return new Err(err) - } - - getWallet = async (): Promise => { - return this.options.wallet ?? (await import("@stellar/freighter-api")).default - } - - getPublicKey = async (): Promise => { - const wallet = await this.getWallet() - if (await wallet.isConnected() && await wallet.isAllowed()) { - return (await wallet.getUserInfo()).publicKey - } - } - - /** - * Get account details from the Soroban network for the publicKey currently - * selected in user's wallet. If not connected to Freighter, use placeholder - * null account. - */ - getAccount = async (): Promise => { - const publicKey = await this.getPublicKey() - return publicKey - ? await this.server.getAccount(publicKey) - : new Account(NULL_ACCOUNT, "0") - } - - /** - * Sign the transaction with the `wallet` (default Freighter), then send to - * the network and return a `SentTransaction` that keeps track of all the - * attempts to send and fetch the transaction from the network. - */ - signAndSend = async ({ secondsToWait = 10, force = false }: { - /** - * Wait `secondsToWait` seconds (default: 10) for both the transaction to SEND successfully (will keep trying if the server returns `TRY_AGAIN_LATER`), as well as for the transaction to COMPLETE (will keep checking if the server returns `PENDING`). - */ - secondsToWait?: number - /** - * If `true`, sign and send the transaction even if it is a read call. - */ - force?: boolean - } = {}): Promise> => { - if (!this.raw) { - throw new Error('Transaction has not yet been simulated') - } - - if (!force && this.isReadCall) { - throw new Error('This is a read call. It requires no signature or sending. Use `force: true` to sign and send anyway.') - } - - if (!await this.hasRealInvoker()) { - throw new WalletDisconnectedError('Wallet is not connected') - } - - if (this.raw.source !== (await this.getAccount()).accountId()) { - throw new Error(`You must submit the transaction with the account that originally created it. Please switch to the wallet with "${this.raw.source}" as its public key.`) - } - - if ((await this.needsNonInvokerSigningBy()).length) { - throw new NeedsMoreSignaturesError( - 'Transaction requires more signatures. See `needsNonInvokerSigningBy` for details.' - ) - } - - return await SentTransaction.init(this.options, this, secondsToWait); - } - - getStorageExpiration = async () => { - const entryRes = await this.server.getLedgerEntries( - new Contract(this.options.contractId).getFootprint() - ) - if ( - !entryRes.entries || - !entryRes.entries.length || - !entryRes.entries[0].liveUntilLedgerSeq - ) throw new Error('failed to get ledger entry') - return entryRes.entries[0].liveUntilLedgerSeq - } - - /** - * Get a list of accounts, other than the invoker of the simulation, that - * need to sign auth entries in this transaction. - * - * Soroban allows multiple people to sign a transaction. Someone needs to - * sign the final transaction envelope; this person/account is called the - * _invoker_, or _source_. Other accounts might need to sign individual auth - * entries in the transaction, if they're not also the invoker. - * - * This function returns a list of accounts that need to sign auth entries, - * assuming that the same invoker/source account will sign the final - * transaction envelope as signed the initial simulation. - * - * One at a time, for each public key in this array, you will need to - * serialize this transaction with `toJSON`, send to the owner of that key, - * deserialize the transaction with `txFromJson`, and call - * {@link signAuthEntries}. Then re-serialize and send to the next account - * in this list. - */ - needsNonInvokerSigningBy = async ({ - includeAlreadySigned = false, - }: { - /** - * Whether or not to include auth entries that have already been signed. Default: false - */ - includeAlreadySigned?: boolean - } = {}): Promise => { - if (!this.raw) { - throw new Error('Transaction has not yet been simulated') - } - - // We expect that any transaction constructed by these libraries has a - // single operation, which is an InvokeHostFunction operation. The host - // function being invoked is the contract method call. - if (!("operations" in this.raw)) { - throw new Error( - `Unexpected Transaction type; no operations: ${JSON.stringify(this.raw) - }` - ) - } - const rawInvokeHostFunctionOp = this.raw - .operations[0] as Operation.InvokeHostFunction - - return [...new Set((rawInvokeHostFunctionOp.auth ?? []).filter(entry => - entry.credentials().switch() === - xdr.SorobanCredentialsType.sorobanCredentialsAddress() && - ( - includeAlreadySigned || - entry.credentials().address().signature().switch().name === 'scvVoid' - ) - ).map(entry => StrKey.encodeEd25519PublicKey( - entry.credentials().address().address().accountId().ed25519() - )))] - } - - preImageFor( - entry: xdr.SorobanAuthorizationEntry, - signatureExpirationLedger: number - ): xdr.HashIdPreimage { - const addrAuth = entry.credentials().address() - return xdr.HashIdPreimage.envelopeTypeSorobanAuthorization( - new xdr.HashIdPreimageSorobanAuthorization({ - networkId: hash(Buffer.from(this.options.networkPassphrase)), - nonce: addrAuth.nonce(), - invocation: entry.rootInvocation(), - signatureExpirationLedger, - }), - ) - } - - /** - * If {@link needsNonInvokerSigningBy} returns a non-empty list, you can serialize - * the transaction with `toJSON`, send it to the owner of one of the public keys - * in the map, deserialize with `txFromJSON`, and call this method on their - * machine. Internally, this will use `signAuthEntry` function from connected - * `wallet` for each. - * - * Then, re-serialize the transaction and either send to the next - * `needsNonInvokerSigningBy` owner, or send it back to the original account - * who simulated the transaction so they can {@link sign} the transaction - * envelope and {@link send} it to the network. - * - * Sending to all `needsNonInvokerSigningBy` owners in parallel is not currently - * supported! - */ - signAuthEntries = async ( - /** - * When to set each auth entry to expire. Could be any number of blocks in - * the future. Can be supplied as a promise or a raw number. Default: - * contract's current `persistent` storage expiration date/ledger - * number/block. - */ - expiration: number | Promise = this.getStorageExpiration() - ): Promise => { - if (!this.raw) throw new Error('Transaction has not yet been assembled or simulated') - const needsNonInvokerSigningBy = await this.needsNonInvokerSigningBy() - - if (!needsNonInvokerSigningBy) throw new NoUnsignedNonInvokerAuthEntriesError('No unsigned non-invoker auth entries; maybe you already signed?') - const publicKey = await this.getPublicKey() - if (!publicKey) throw new Error('Could not get public key from wallet; maybe Freighter is not signed in?') - if (needsNonInvokerSigningBy.indexOf(publicKey) === -1) throw new Error(`No auth entries for public key "${publicKey}"`) - const wallet = await this.getWallet() - - const rawInvokeHostFunctionOp = this.raw - .operations[0] as Operation.InvokeHostFunction - - const authEntries = rawInvokeHostFunctionOp.auth ?? [] - - for (const [i, entry] of authEntries.entries()) { - if ( - entry.credentials().switch() !== - xdr.SorobanCredentialsType.sorobanCredentialsAddress() - ) { - // if the invoker/source account, then the entry doesn't need explicit - // signature, since the tx envelope is already signed by the source - // account, so only check for sorobanCredentialsAddress - continue - } - const pk = StrKey.encodeEd25519PublicKey( - entry.credentials().address().address().accountId().ed25519() - ) - - // this auth entry needs to be signed by a different account - // (or maybe already was!) - if (pk !== publicKey) continue - - authEntries[i] = await authorizeEntry( - entry, - async preimage => Buffer.from( - await wallet.signAuthEntry(preimage.toXDR('base64')), - 'base64' - ), - await expiration, - this.options.networkPassphrase - ) - } - } - - get isReadCall(): boolean { - const authsCount = this.simulationData.result.auth.length; - const writeLength = this.simulationData.transactionData.resources().footprint().readWrite().length - return (authsCount === 0) && (writeLength === 0); - } - - hasRealInvoker = async (): Promise => { - const account = await this.getAccount() - return account.accountId() !== NULL_ACCOUNT - } -} - -/** - * A transaction that has been sent to the Soroban network. This happens in two steps: - * - * 1. `sendTransaction`: initial submission of the transaction to the network. - * This step can run into problems, and will be retried with exponential - * backoff if it does. See all attempts in `sendTransactionResponseAll` and the - * most recent attempt in `sendTransactionResponse`. - * 2. `getTransaction`: once the transaction has been submitted to the network - * successfully, you need to wait for it to finalize to get the results of the - * transaction. This step can also run into problems, and will be retried with - * exponential backoff if it does. See all attempts in - * `getTransactionResponseAll` and the most recent attempt in - * `getTransactionResponse`. - */ -class SentTransaction { - public server: SorobanRpc.Server - public signed: Tx - public sendTransactionResponse?: SendTx - public sendTransactionResponseAll?: SendTx[] - public getTransactionResponse?: GetTx - public getTransactionResponseAll?: GetTx[] - - constructor(public options: AssembledTransactionOptions, public assembled: AssembledTransaction) { - this.server = new SorobanRpc.Server(this.options.rpcUrl, { - allowHttp: this.options.rpcUrl.startsWith("http://"), - }); - this.assembled = assembled - } - - static init = async ( - options: AssembledTransactionOptions, - assembled: AssembledTransaction, - secondsToWait: number = 10 - ): Promise> => { - const tx = new SentTransaction(options, assembled) - return await tx.send(secondsToWait) - } - - private send = async (secondsToWait: number = 10): Promise => { - const wallet = await this.assembled.getWallet() - - this.sendTransactionResponseAll = await withExponentialBackoff( - async (previousFailure) => { - if (previousFailure) { - // Increment transaction sequence number and resimulate before trying again - - // Soroban transaction can only have 1 operation - const op = this.assembled.raw.operations[0] as Operation.InvokeHostFunction; - - this.assembled.raw = new TransactionBuilder(await this.assembled.getAccount(), { - fee: this.assembled.raw.fee, - networkPassphrase: this.options.networkPassphrase, - }) - .setTimeout(TimeoutInfinite) - .addOperation( - Operation.invokeHostFunction({ ...op, auth: op.auth ?? [] }), - ) - .build() - - await this.assembled.simulate() - } - - const signature = await wallet.signTransaction(this.assembled.raw.toXDR(), { - networkPassphrase: this.options.networkPassphrase, - }); - - this.signed = TransactionBuilder.fromXDR( - signature, - this.options.networkPassphrase - ) as Tx - - return this.server.sendTransaction(this.signed) - }, - resp => resp.status !== "PENDING", - secondsToWait - ) - - this.sendTransactionResponse = this.sendTransactionResponseAll[this.sendTransactionResponseAll.length - 1] - - if (this.sendTransactionResponse.status !== "PENDING") { - throw new Error( - `Tried to resubmit transaction for ${secondsToWait - } seconds, but it's still failing. ` + - `All attempts: ${JSON.stringify( - this.sendTransactionResponseAll, - null, - 2 - )}` - ); - } - - const { hash } = this.sendTransactionResponse - - this.getTransactionResponseAll = await withExponentialBackoff( - () => this.server.getTransaction(hash), - resp => resp.status === SorobanRpc.Api.GetTransactionStatus.NOT_FOUND, - secondsToWait - ) - - this.getTransactionResponse = this.getTransactionResponseAll[this.getTransactionResponseAll.length - 1] - if (this.getTransactionResponse.status === SorobanRpc.Api.GetTransactionStatus.NOT_FOUND) { - console.error( - `Waited ${secondsToWait - } seconds for transaction to complete, but it did not. ` + - `Returning anyway. Check the transaction status manually. ` + - `Sent transaction: ${JSON.stringify( - this.sendTransactionResponse, - null, - 2 - )}\n` + - `All attempts to get the result: ${JSON.stringify( - this.getTransactionResponseAll, - null, - 2 - )}` - ); - } - - return this; - } - - get result(): T { - // 1. check if transaction was submitted and awaited with `getTransaction` - if ( - "getTransactionResponse" in this && - this.getTransactionResponse - ) { - // getTransactionResponse has a `returnValue` field unless it failed - if ("returnValue" in this.getTransactionResponse) { - return this.options.parseResultXdr(this.getTransactionResponse.returnValue!) - } - - // if "returnValue" not present, the transaction failed; return without parsing the result - throw new Error("Transaction failed! Cannot parse result.") - } - - // 2. otherwise, maybe it was merely sent with `sendTransaction` - if (this.sendTransactionResponse) { - const errorResult = this.sendTransactionResponse.errorResult?.result() - if (errorResult) { - throw new SendFailedError( - `Transaction simulation looked correct, but attempting to send the transaction failed. Check \`simulation\` and \`sendTransactionResponseAll\` to troubleshoot. Decoded \`sendTransactionResponse.errorResultXdr\`: ${errorResult}` - ) - } - throw new SendResultOnlyError( - `Transaction was sent to the network, but not yet awaited. No result to show. Await transaction completion with \`getTransaction(sendTransactionResponse.hash)\`` - ) - } - - // 3. finally, if neither of those are present, throw an error - throw new Error(`Sending transaction failed: ${JSON.stringify(this.assembled)}`) - } -} - -/** - * Keep calling a `fn` for `secondsToWait` seconds, if `keepWaitingIf` is true. - * Returns an array of all attempts to call the function. - */ -async function withExponentialBackoff( - fn: (previousFailure?: T) => Promise, - keepWaitingIf: (result: T) => boolean, - secondsToWait: number, - exponentialFactor = 1.5, - verbose = false, -): Promise { - const attempts: T[] = [] - - let count = 0 - attempts.push(await fn()) - if (!keepWaitingIf(attempts[attempts.length - 1])) return attempts - - const waitUntil = new Date(Date.now() + secondsToWait * 1000).valueOf() - let waitTime = 1000 - let totalWaitTime = waitTime - - while (Date.now() < waitUntil && keepWaitingIf(attempts[attempts.length - 1])) { - count++ - // Wait a beat - if (verbose) { - console.info(`Waiting ${waitTime}ms before trying again (bringing the total wait time to ${totalWaitTime}ms so far, of total ${secondsToWait * 1000}ms)`) - } - await new Promise(res => setTimeout(res, waitTime)) - // Exponential backoff - waitTime = waitTime * exponentialFactor; - if (new Date(Date.now() + waitTime).valueOf() > waitUntil) { - waitTime = waitUntil - Date.now() - if (verbose) { - console.info(`was gonna wait too long; new waitTime: ${waitTime}ms`) - } - } - totalWaitTime = waitTime + totalWaitTime - // Try again - attempts.push(await fn(attempts[attempts.length - 1])) - if (verbose && keepWaitingIf(attempts[attempts.length - 1])) { - console.info( - `${count}. Called ${fn}; ${attempts.length - } prev attempts. Most recent: ${JSON.stringify(attempts[attempts.length - 1], null, 2) - }` - ) - } - } - - return attempts -} diff --git a/cmd/crates/soroban-spec-typescript/src/project_template/src/index.ts b/cmd/crates/soroban-spec-typescript/src/project_template/src/index.ts index f7ad0b66cc..a2e0bce209 100644 --- a/cmd/crates/soroban-spec-typescript/src/project_template/src/index.ts +++ b/cmd/crates/soroban-spec-typescript/src/project_template/src/index.ts @@ -1,6 +1,10 @@ import { ContractSpec, Address } from '@stellar/stellar-sdk'; import { Buffer } from "buffer"; -import { AssembledTransaction, Ok, Err } from './assembled-tx.js'; +import { + AssembledTransaction, + ContractClient, + ContractClientOptions, +} from '@stellar/stellar-sdk/lib/contract_client/index.js'; import type { u32, i32, @@ -13,13 +17,11 @@ import type { Option, Typepoint, Duration, - Error_, - Result, -} from './assembled-tx.js'; -import type { ClassOptions, XDR_BASE64 } from './method-options.js'; - -export * from './assembled-tx.js'; -export * from './method-options.js'; +} from '@stellar/stellar-sdk/lib/contract_client'; +import { Result } from '@stellar/stellar-sdk/lib/rust_types/index.js'; +export * from '@stellar/stellar-sdk' +export * from '@stellar/stellar-sdk/lib/contract_client/index.js' +export * from '@stellar/stellar-sdk/lib/rust_types/index.js' if (typeof window !== 'undefined') { //@ts-ignore Buffer exists diff --git a/cmd/crates/soroban-spec-typescript/src/project_template/src/method-options.ts b/cmd/crates/soroban-spec-typescript/src/project_template/src/method-options.ts deleted file mode 100644 index d1ff142f97..0000000000 --- a/cmd/crates/soroban-spec-typescript/src/project_template/src/method-options.ts +++ /dev/null @@ -1,50 +0,0 @@ -// defined this way so typeahead shows full union, not named alias -let responseTypes: 'simulated' | 'full' | undefined -export type ResponseTypes = typeof responseTypes - -export type XDR_BASE64 = string - -export interface Wallet { - isConnected: () => Promise, - isAllowed: () => Promise, - getUserInfo: () => Promise<{ publicKey?: string }>, - signTransaction: (tx: XDR_BASE64, opts?: { - network?: string, - networkPassphrase?: string, - accountToSign?: string, - }) => Promise, - signAuthEntry: ( - entryXdr: XDR_BASE64, - opts?: { - accountToSign?: string; - } - ) => Promise -} - -export type ClassOptions = { - contractId: string - networkPassphrase: string - rpcUrl: string - errorTypes?: Record - /** - * A Wallet interface, such as Freighter, that has the methods `isConnected`, `isAllowed`, `getUserInfo`, and `signTransaction`. If not provided, will attempt to import and use Freighter. Example: - * - * @example - * ```ts - * import freighter from "@stellar/freighter-api"; - * import { Contract } from "INSERT_CONTRACT_NAME_HERE"; - * const contract = new Contract({ - * …, - * wallet: freighter, - * }) - * ``` - */ - wallet?: Wallet -} - -export type MethodOptions = { - /** - * The fee to pay for the transaction. Default: soroban-sdk's BASE_FEE ('100') - */ - fee?: number -} diff --git a/cmd/crates/soroban-spec-typescript/ts-tests/.env b/cmd/crates/soroban-spec-typescript/ts-tests/.env index 39b2454824..93bb4be673 100644 --- a/cmd/crates/soroban-spec-typescript/ts-tests/.env +++ b/cmd/crates/soroban-spec-typescript/ts-tests/.env @@ -1,2 +1,3 @@ SOROBAN_NETWORK_PASSPHRASE="Standalone Network ; February 2017" SOROBAN_RPC_URL="http://localhost:8000/soroban/rpc" +SOROBAN_FRIENDBOT_URL="http://localhost:8000/friendbot" diff --git a/cmd/crates/soroban-spec-typescript/ts-tests/package-lock.json b/cmd/crates/soroban-spec-typescript/ts-tests/package-lock.json index 36f5cdd63b..0147ef4f12 100644 --- a/cmd/crates/soroban-spec-typescript/ts-tests/package-lock.json +++ b/cmd/crates/soroban-spec-typescript/ts-tests/package-lock.json @@ -7,7 +7,7 @@ "hasInstallScript": true, "devDependencies": { "@ava/typescript": "^4.1.0", - "@stellar/stellar-sdk": "11.2.0", + "@stellar/stellar-sdk": "stellar/js-stellar-sdk#bindings", "@types/node": "^20.4.9", "@typescript-eslint/eslint-plugin": "^6.10.0", "@typescript-eslint/parser": "^6.10.0", @@ -86,29 +86,73 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/@eslint/eslintrc/node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@eslint/eslintrc/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/@eslint/js": { - "version": "8.55.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.55.0.tgz", - "integrity": "sha512-qQfo2mxH5yVom1kacMtZZJFVdW+E70mqHMJvVg6WTLo+VBuQJ4TojZlfWBjK0ve5BdEeNAVxOsl/nvNMpJOaJA==", + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.0.tgz", + "integrity": "sha512-Ys+3g2TaW7gADOJzPt83SJtCDhMjndcDMFVQ/Tj9iA1BfJzFKD9mAUXT3OenpuPHbI6P/myECxRJrofUsDx/5g==", "dev": true, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, "node_modules/@humanwhocodes/config-array": { - "version": "0.11.13", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.13.tgz", - "integrity": "sha512-JSBDMiDKSzQVngfRjOdFXgFfklaXI4K9nLF49Auh21lmBWRLIK3+xTErTWD4KU54pb6coM6ESE7Awz/FNU3zgQ==", + "version": "0.11.14", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.14.tgz", + "integrity": "sha512-3T8LkOmg45BV5FICb15QQMsyUSWrQ8AygVfC7ZG32zOalnqrilm018ZVCw0eapXux8FtA33q8PSRSstjee3jSg==", "dev": true, "dependencies": { - "@humanwhocodes/object-schema": "^2.0.1", - "debug": "^4.1.1", + "@humanwhocodes/object-schema": "^2.0.2", + "debug": "^4.3.1", "minimatch": "^3.0.5" }, "engines": { "node": ">=10.10.0" } }, + "node_modules/@humanwhocodes/config-array/node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@humanwhocodes/config-array/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/@humanwhocodes/module-importer": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", @@ -123,9 +167,9 @@ } }, "node_modules/@humanwhocodes/object-schema": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.1.tgz", - "integrity": "sha512-dvuCeX5fC9dXgJn9t+X5atfmgQAzUOWqS1254Gh0m6i8wKd10ebXkfNKiRK+1GWi/yTvvLDHpoxLr0xxxeslWw==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.2.tgz", + "integrity": "sha512-6EwiSjwWYP7pTckG6I5eyFANjPhmPjUX9JRLUSfNPC7FX7zK9gyZAfUEaECL6ALTpGX5AjnBq3C9XmVWPitNpw==", "dev": true }, "node_modules/@nodelib/fs.scandir": { @@ -164,40 +208,42 @@ } }, "node_modules/@stellar/js-xdr": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@stellar/js-xdr/-/js-xdr-3.0.1.tgz", - "integrity": "sha512-dp5Eh7Nr1YjiIeqpdkj2cQYxfoPudDAH3ck8MWggp48Htw66Z/hUssNYUQG/OftLjEmHT90Z/dtey2Y77DOxIw==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@stellar/js-xdr/-/js-xdr-3.1.0.tgz", + "integrity": "sha512-mYTyFnhgyQgyvpAYZRO1LurUn2MxcIZRj74zZz/BxKEk7zrL4axhQ1ez0HL2BRi0wlG6cHn5BeD/t9Xcyp7CSQ==", "dev": true }, "node_modules/@stellar/stellar-base": { - "version": "10.0.1", - "resolved": "https://registry.npmjs.org/@stellar/stellar-base/-/stellar-base-10.0.1.tgz", - "integrity": "sha512-BDbx7VHOEQh+4J3Q+gStNXgPaNckVFmD4aOlBBGwxlF6vPFmVnW8IoJdkX7T58zpX55eWI6DXvEhDBlrqTlhAQ==", + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/@stellar/stellar-base/-/stellar-base-11.0.0.tgz", + "integrity": "sha512-KPTjaWJCG2m7hMCPRWFGGPaG5qOkgPLWvFVOhe1HUy7dlE4MxxPfdusz0mcLkf6VT7doqhLB1rIt0D9M2GgQcQ==", "dev": true, "dependencies": { - "@stellar/js-xdr": "^3.0.1", + "@stellar/js-xdr": "^3.1.0", "base32.js": "^0.1.0", "bignumber.js": "^9.1.2", "buffer": "^6.0.3", "sha.js": "^2.3.6", - "tweetnacl": "^1.0.3" + "tweetnacl": "^1.0.3", + "typescript": "^5.3.3" }, "optionalDependencies": { - "sodium-native": "^4.0.1" + "sodium-native": "^4.0.8" } }, "node_modules/@stellar/stellar-sdk": { - "version": "11.2.0", - "resolved": "https://registry.npmjs.org/@stellar/stellar-sdk/-/stellar-sdk-11.2.0.tgz", - "integrity": "sha512-qInRR+mLLl9O/AI6Q+Sr19RZeYJtlNoJQJi3pch5BYoMvVhjO8IU8AhHADP//Zmc2osyogwPuqXBiFdaGlfHWA==", + "version": "11.2.2", + "resolved": "git+ssh://git@github.com/stellar/js-stellar-sdk.git#bdf74951f89bbc9bd48179b4a7a4ad33db570643", "dev": true, + "license": "Apache-2.0", "dependencies": { - "@stellar/stellar-base": "10.0.1", - "axios": "^1.6.5", + "@stellar/stellar-base": "^11.0.0", + "axios": "^1.6.7", "bignumber.js": "^9.1.2", "eventsource": "^2.0.2", "randombytes": "^2.1.0", "toml": "^3.0.0", + "typescript": "^5.3.3", "urijs": "^1.19.1" } }, @@ -208,31 +254,31 @@ "dev": true }, "node_modules/@types/node": { - "version": "20.10.4", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.10.4.tgz", - "integrity": "sha512-D08YG6rr8X90YB56tSIuBaddy/UXAA9RKJoFvrsnogAum/0pmjkgi4+2nx96A330FmioegBWmEYQ+syqCFaveg==", + "version": "20.11.26", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.26.tgz", + "integrity": "sha512-YwOMmyhNnAWijOBQweOJnQPl068Oqd4K3OFbTc6AHJwzweUwwWG3GIFY74OKks2PJUDkQPeddOQES9mLn1CTEQ==", "dev": true, "dependencies": { "undici-types": "~5.26.4" } }, "node_modules/@types/semver": { - "version": "7.5.6", - "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.6.tgz", - "integrity": "sha512-dn1l8LaMea/IjDoHNd9J52uBbInB796CDffS6VdIxvqYCPSG0V0DzHp76GpaWnlhg88uYyPbXCDIowa86ybd5A==", + "version": "7.5.8", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.8.tgz", + "integrity": "sha512-I8EUhyrgfLrcTkzV3TSsGyl1tSuPrEDzr0yd5m90UgNxQkyDXULk3b6MlQqTCpZpNtWe1K0hzclnZkTcLBe2UQ==", "dev": true }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.14.0.tgz", - "integrity": "sha512-1ZJBykBCXaSHG94vMMKmiHoL0MhNHKSVlcHVYZNw+BKxufhqQVTOawNpwwI1P5nIFZ/4jLVop0mcY6mJJDFNaw==", + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.21.0.tgz", + "integrity": "sha512-oy9+hTPCUFpngkEZUSzbf9MxI65wbKFoQYsgPdILTfbUldp5ovUuphZVe4i30emU9M/kP+T64Di0mxl7dSw3MA==", "dev": true, "dependencies": { "@eslint-community/regexpp": "^4.5.1", - "@typescript-eslint/scope-manager": "6.14.0", - "@typescript-eslint/type-utils": "6.14.0", - "@typescript-eslint/utils": "6.14.0", - "@typescript-eslint/visitor-keys": "6.14.0", + "@typescript-eslint/scope-manager": "6.21.0", + "@typescript-eslint/type-utils": "6.21.0", + "@typescript-eslint/utils": "6.21.0", + "@typescript-eslint/visitor-keys": "6.21.0", "debug": "^4.3.4", "graphemer": "^1.4.0", "ignore": "^5.2.4", @@ -258,15 +304,15 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.14.0.tgz", - "integrity": "sha512-QjToC14CKacd4Pa7JK4GeB/vHmWFJckec49FR4hmIRf97+KXole0T97xxu9IFiPxVQ1DBWrQ5wreLwAGwWAVQA==", + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.21.0.tgz", + "integrity": "sha512-tbsV1jPne5CkFQCgPBcDOt30ItF7aJoZL997JSF7MhGQqOeT3svWRYxiqlfA5RUdlHN6Fi+EI9bxqbdyAUZjYQ==", "dev": true, "dependencies": { - "@typescript-eslint/scope-manager": "6.14.0", - "@typescript-eslint/types": "6.14.0", - "@typescript-eslint/typescript-estree": "6.14.0", - "@typescript-eslint/visitor-keys": "6.14.0", + "@typescript-eslint/scope-manager": "6.21.0", + "@typescript-eslint/types": "6.21.0", + "@typescript-eslint/typescript-estree": "6.21.0", + "@typescript-eslint/visitor-keys": "6.21.0", "debug": "^4.3.4" }, "engines": { @@ -286,13 +332,13 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-6.14.0.tgz", - "integrity": "sha512-VT7CFWHbZipPncAZtuALr9y3EuzY1b1t1AEkIq2bTXUPKw+pHoXflGNG5L+Gv6nKul1cz1VH8fz16IThIU0tdg==", + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-6.21.0.tgz", + "integrity": "sha512-OwLUIWZJry80O99zvqXVEioyniJMa+d2GrqpUTqi5/v5D5rOrppJVBPa0yKCblcigC0/aYAzxxqQ1B+DS2RYsg==", "dev": true, "dependencies": { - "@typescript-eslint/types": "6.14.0", - "@typescript-eslint/visitor-keys": "6.14.0" + "@typescript-eslint/types": "6.21.0", + "@typescript-eslint/visitor-keys": "6.21.0" }, "engines": { "node": "^16.0.0 || >=18.0.0" @@ -303,13 +349,13 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-6.14.0.tgz", - "integrity": "sha512-x6OC9Q7HfYKqjnuNu5a7kffIYs3No30isapRBJl1iCHLitD8O0lFbRcVGiOcuyN837fqXzPZ1NS10maQzZMKqw==", + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-6.21.0.tgz", + "integrity": "sha512-rZQI7wHfao8qMX3Rd3xqeYSMCL3SoiSQLBATSiVKARdFGCYSRvmViieZjqc58jKgs8Y8i9YvVVhRbHSTA4VBag==", "dev": true, "dependencies": { - "@typescript-eslint/typescript-estree": "6.14.0", - "@typescript-eslint/utils": "6.14.0", + "@typescript-eslint/typescript-estree": "6.21.0", + "@typescript-eslint/utils": "6.21.0", "debug": "^4.3.4", "ts-api-utils": "^1.0.1" }, @@ -330,9 +376,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-6.14.0.tgz", - "integrity": "sha512-uty9H2K4Xs8E47z3SnXEPRNDfsis8JO27amp2GNCnzGETEW3yTqEIVg5+AI7U276oGF/tw6ZA+UesxeQ104ceA==", + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-6.21.0.tgz", + "integrity": "sha512-1kFmZ1rOm5epu9NZEZm1kckCDGj5UJEf7P1kliH4LKu/RkwpsfqqGmY2OOcUs18lSlQBKLDYBOGxRVtrMN5lpg==", "dev": true, "engines": { "node": "^16.0.0 || >=18.0.0" @@ -343,16 +389,17 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-6.14.0.tgz", - "integrity": "sha512-yPkaLwK0yH2mZKFE/bXkPAkkFgOv15GJAUzgUVonAbv0Hr4PK/N2yaA/4XQbTZQdygiDkpt5DkxPELqHguNvyw==", + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-6.21.0.tgz", + "integrity": "sha512-6npJTkZcO+y2/kr+z0hc4HwNfrrP4kNYh57ek7yCNlrBjWQ1Y0OS7jiZTkgumrvkX5HkEKXFZkkdFNkaW2wmUQ==", "dev": true, "dependencies": { - "@typescript-eslint/types": "6.14.0", - "@typescript-eslint/visitor-keys": "6.14.0", + "@typescript-eslint/types": "6.21.0", + "@typescript-eslint/visitor-keys": "6.21.0", "debug": "^4.3.4", "globby": "^11.1.0", "is-glob": "^4.0.3", + "minimatch": "9.0.3", "semver": "^7.5.4", "ts-api-utils": "^1.0.1" }, @@ -370,17 +417,17 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-6.14.0.tgz", - "integrity": "sha512-XwRTnbvRr7Ey9a1NT6jqdKX8y/atWG+8fAIu3z73HSP8h06i3r/ClMhmaF/RGWGW1tHJEwij1uEg2GbEmPYvYg==", + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-6.21.0.tgz", + "integrity": "sha512-NfWVaC8HP9T8cbKQxHcsJBY5YE1O33+jpMwN45qzWWaPDZgLIbo12toGMWnmhvCpd3sIxkpDw3Wv1B3dYrbDQQ==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.4.0", "@types/json-schema": "^7.0.12", "@types/semver": "^7.5.0", - "@typescript-eslint/scope-manager": "6.14.0", - "@typescript-eslint/types": "6.14.0", - "@typescript-eslint/typescript-estree": "6.14.0", + "@typescript-eslint/scope-manager": "6.21.0", + "@typescript-eslint/types": "6.21.0", + "@typescript-eslint/typescript-estree": "6.21.0", "semver": "^7.5.4" }, "engines": { @@ -395,12 +442,12 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.14.0.tgz", - "integrity": "sha512-fB5cw6GRhJUz03MrROVuj5Zm/Q+XWlVdIsFj+Zb1Hvqouc8t+XP2H5y53QYU/MGtd2dPg6/vJJlhoX3xc2ehfw==", + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.21.0.tgz", + "integrity": "sha512-JJtkDduxLi9bivAB+cYOVMtbkqdPOhZ+ZI5LC47MIRrDV4Yn2o+ZnW10Nkmr28xRpSpdJ6Sm42Hjf2+REYXm0A==", "dev": true, "dependencies": { - "@typescript-eslint/types": "6.14.0", + "@typescript-eslint/types": "6.21.0", "eslint-visitor-keys": "^3.4.1" }, "engines": { @@ -418,9 +465,9 @@ "dev": true }, "node_modules/acorn": { - "version": "8.11.2", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.2.tgz", - "integrity": "sha512-nc0Axzp/0FILLEVsm4fNwLCwMttvhEI263QtVPQcbpfZZ3ts0hLsZGOpE6czNlid7CJ9MlyH8reXkpsf3YUY4w==", + "version": "8.11.3", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz", + "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==", "dev": true, "bin": { "acorn": "bin/acorn" @@ -439,9 +486,9 @@ } }, "node_modules/acorn-walk": { - "version": "8.3.1", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.1.tgz", - "integrity": "sha512-TgUZgYvqZprrl7YldZNoa9OciCAyZR+Ejm9eXzKCmjsF5IKp/wgQ7Z/ZpjpGTIUPwrHQIcYeI8qDh4PsEwxMbw==", + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.2.tgz", + "integrity": "sha512-cjkyv4OtNCIeqhHrfS81QWXoCBPExR/J62oyEqepVw8WaQeSqpW2uhuLPh1m9eWhDuOo/jUXVTlifvesOWp/4A==", "dev": true, "engines": { "node": ">=0.4.0" @@ -664,9 +711,9 @@ } }, "node_modules/axios": { - "version": "1.6.5", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.5.tgz", - "integrity": "sha512-Ii012v05KEVuUoFWmMW/UQv9aRIc3ZwkWDcM+h5Il8izZCtRVpDUfwpoFf7eOtajT3QiGR4yDUx7lPqHJULgbg==", + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.7.tgz", + "integrity": "sha512-/hDJGff6/c7u0hDkvkGxR/oy6CbCs8ziCsC7SqmhjfozqiJGc8Z11wrv9z9lYfY4K8l+H9TpjcMDX0xOZmx+RA==", "dev": true, "dependencies": { "follow-redirects": "^1.15.4", @@ -734,13 +781,12 @@ "dev": true }, "node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", "dev": true, "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" + "balanced-match": "^1.0.0" } }, "node_modules/braces": { @@ -816,16 +862,10 @@ } }, "node_modules/chokidar": { - "version": "3.5.3", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", - "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://paulmillr.com/funding/" - } - ], "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", @@ -838,6 +878,9 @@ "engines": { "node": ">= 8.10.0" }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, "optionalDependencies": { "fsevents": "~2.3.2" } @@ -1156,15 +1199,15 @@ } }, "node_modules/dotenv": { - "version": "16.3.1", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz", - "integrity": "sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==", + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz", + "integrity": "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==", "dev": true, "engines": { "node": ">=12" }, "funding": { - "url": "https://github.com/motdotla/dotenv?sponsor=1" + "url": "https://dotenvx.com" } }, "node_modules/eastasianwidth": { @@ -1174,9 +1217,9 @@ "dev": true }, "node_modules/emittery": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/emittery/-/emittery-1.0.1.tgz", - "integrity": "sha512-2ID6FdrMD9KDLldGesP6317G78K7km/kMcwItRtVFva7I/cSEOIaLpewaUb+YLXVwdAp3Ctfxh/V5zIl1sj7dQ==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/emittery/-/emittery-1.0.3.tgz", + "integrity": "sha512-tJdCJitoy2lrC2ldJcqN4vkqJ00lT+tOWNT1hBJjO/3FDMJa5TTIiYGCKGkn/WfCyOzUMObeohbVTj00fhiLiA==", "dev": true, "engines": { "node": ">=14.16" @@ -1192,9 +1235,9 @@ "dev": true }, "node_modules/escalade": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", - "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.2.tgz", + "integrity": "sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==", "dev": true, "engines": { "node": ">=6" @@ -1213,16 +1256,16 @@ } }, "node_modules/eslint": { - "version": "8.55.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.55.0.tgz", - "integrity": "sha512-iyUUAM0PCKj5QpwGfmCAG9XXbZCWsqP/eWAWrG/W0umvjuLRBECwSFdt+rCntju0xEH7teIABPwXpahftIaTdA==", + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.0.tgz", + "integrity": "sha512-dZ6+mexnaTIbSBZWgou51U6OmzIhYM2VcNdtiTtI7qPNZm35Akpr0f6vtw3w1Kmn5PYo+tZVfh13WrhpS6oLqQ==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", "@eslint/eslintrc": "^2.1.4", - "@eslint/js": "8.55.0", - "@humanwhocodes/config-array": "^0.11.13", + "@eslint/js": "8.57.0", + "@humanwhocodes/config-array": "^0.11.14", "@humanwhocodes/module-importer": "^1.0.1", "@nodelib/fs.walk": "^1.2.8", "@ungap/structured-clone": "^1.2.0", @@ -1319,6 +1362,16 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/eslint/node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, "node_modules/eslint/node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -1359,6 +1412,18 @@ "node": ">=10.13.0" } }, + "node_modules/eslint/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/eslint/node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -1516,9 +1581,9 @@ "dev": true }, "node_modules/fastq": { - "version": "1.15.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.15.0.tgz", - "integrity": "sha512-wBrocU2LCXXa+lWBt8RoIRD89Fi8OdABODa/kEnyeyjS5aZO5/GNvI5sEINADqP/h8M29UHTHUb53sUu5Ihqdw==", + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.17.1.tgz", + "integrity": "sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w==", "dev": true, "dependencies": { "reusify": "^1.0.4" @@ -1595,15 +1660,15 @@ } }, "node_modules/flatted": { - "version": "3.2.9", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.9.tgz", - "integrity": "sha512-36yxDn5H7OFZQla0/jFJmbIKTdZAQHngCedGxiMmpNfEZM0sdEeT+WczLQrjK6D7o2aiyLYDnkw0R3JK0Qv1RQ==", + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.1.tgz", + "integrity": "sha512-X8cqMLLie7KsNUDSdzeN8FYK9rEt4Dt67OsG/DNGnYTSDBG4uFAJFBnUeiV+zCVAvwFy56IjM9sH51jVaEhNxw==", "dev": true }, "node_modules/follow-redirects": { - "version": "1.15.4", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.4.tgz", - "integrity": "sha512-Cr4D/5wlrb0z9dgERpUL3LrmPKVDsETIJhaCMeDfuFYcqa5bldGV6wBsAN6X/vxlXQtFBMrXdXxdL8CbDTGniw==", + "version": "1.15.5", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz", + "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==", "dev": true, "funding": [ { @@ -1707,6 +1772,28 @@ "node": ">= 6" } }, + "node_modules/glob/node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/globals": { "version": "13.24.0", "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", @@ -1787,9 +1874,9 @@ ] }, "node_modules/ignore": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.0.tgz", - "integrity": "sha512-g7dmpshy+gD7mh88OC9NwSGTKoc3kyLAZQRU1mt53Aw/vnvfXnbC+F/7F7QoYVKbV+KNvJx8wArewKy1vXMtlg==", + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.1.tgz", + "integrity": "sha512-5Fytz/IraMjqpwfd34ke28PTVMjZjJG2MPn5t7OE4eUCUNf8BAa7b5WUS9/Qvr6mwOQS7Mk6vdsMno5he+T8Xw==", "dev": true, "engines": { "node": ">= 4" @@ -2209,15 +2296,18 @@ } }, "node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.3.tgz", + "integrity": "sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg==", "dev": true, "dependencies": { - "brace-expansion": "^1.1.7" + "brace-expansion": "^2.0.1" }, "engines": { - "node": "*" + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, "node_modules/ms": { @@ -2233,9 +2323,9 @@ "dev": true }, "node_modules/node-gyp-build": { - "version": "4.7.1", - "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.7.1.tgz", - "integrity": "sha512-wTSrZ+8lsRRa3I3H8Xr65dLWSgCvY2l4AOnaeKdPA9TB/WYMPaTcrzf3rXvFoVvjKNVnu0CcWSx54qq9GKRUYg==", + "version": "4.8.0", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.0.tgz", + "integrity": "sha512-u6fs2AEUljNho3EYTJNBfImO5QTo/J/1Etd+NVdCj7qWKUSN/bSLkZwhDv7I+w/MSC6qJ4cknepkAYykDdK8og==", "dev": true, "optional": true, "bin": { @@ -2263,9 +2353,9 @@ } }, "node_modules/npm-run-path": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.1.0.tgz", - "integrity": "sha512-sJOdmRGrY2sjNTRMbSvluQqg+8X7ZK61yvzBEIDhz4f8z1TZFYABsqjjCBd/0PUNE9M6QDgHJXQkGUEm7Q+l9Q==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz", + "integrity": "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==", "dev": true, "dependencies": { "path-key": "^4.0.0" @@ -2793,9 +2883,9 @@ ] }, "node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.0.tgz", + "integrity": "sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==", "dev": true, "dependencies": { "lru-cache": "^6.0.0" @@ -2900,9 +2990,9 @@ } }, "node_modules/sodium-native": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/sodium-native/-/sodium-native-4.0.4.tgz", - "integrity": "sha512-faqOKw4WQKK7r/ybn6Lqo1F9+L5T6NlBJJYvpxbZPetpWylUVqz449mvlwIBKBqxEHbWakWuOlUt8J3Qpc4sWw==", + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/sodium-native/-/sodium-native-4.0.10.tgz", + "integrity": "sha512-vrJQt4gASntDbnltRRk9vN4rks1SehjM12HkqQtu250JtWT+/lo8oEOa1HvSq3+8hzJdYcCJuLR5qRGxoRDjAg==", "dev": true, "hasInstallScript": true, "optional": true, @@ -3085,12 +3175,12 @@ "dev": true }, "node_modules/ts-api-utils": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.0.3.tgz", - "integrity": "sha512-wNMeqtMz5NtwpT/UZGY5alT+VoKdSsOOP/kqHFcUW1P/VRhH2wJ48+DN2WwUliNbQ976ETwDL0Ifd2VVvgonvg==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.3.0.tgz", + "integrity": "sha512-UQMIo7pb8WRomKR1/+MFVLTroIvDVtMX3K6OUir8ynLyzB8Jeriont2bTAtmNPa1ekAgN7YPDyf6V+ygrdU+eQ==", "dev": true, "engines": { - "node": ">=16.13.0" + "node": ">=16" }, "peerDependencies": { "typescript": ">=4.2.0" @@ -3127,9 +3217,9 @@ } }, "node_modules/typescript": { - "version": "5.3.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.3.3.tgz", - "integrity": "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==", + "version": "5.4.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.2.tgz", + "integrity": "sha512-+2/g0Fds1ERlP6JsakQQDXjZdZMM+rqpamFZJEKh4kwTIn3iDkgKtby0CeNd5ATNZ4Ry1ax15TMx0W2V+miizQ==", "dev": true, "bin": { "tsc": "bin/tsc", diff --git a/cmd/crates/soroban-spec-typescript/ts-tests/package.json b/cmd/crates/soroban-spec-typescript/ts-tests/package.json index c06446de37..6767934340 100644 --- a/cmd/crates/soroban-spec-typescript/ts-tests/package.json +++ b/cmd/crates/soroban-spec-typescript/ts-tests/package.json @@ -14,7 +14,7 @@ "ava": "^5.3.1", "dotenv": "^16.3.1", "eslint": "^8.53.0", - "@stellar/stellar-sdk": "11.2.0", + "@stellar/stellar-sdk": "stellar/js-stellar-sdk#bindings", "typescript": "^5.3.3" }, "ava": { diff --git a/cmd/crates/soroban-spec-typescript/ts-tests/src/test-custom-types.ts b/cmd/crates/soroban-spec-typescript/ts-tests/src/test-custom-types.ts index 3b07dc3d42..c5643f920f 100644 --- a/cmd/crates/soroban-spec-typescript/ts-tests/src/test-custom-types.ts +++ b/cmd/crates/soroban-spec-typescript/ts-tests/src/test-custom-types.ts @@ -1,10 +1,17 @@ import test from 'ava' -import { root, rpcUrl, wallet } from './util.js' -import { Contract, Ok, Err, networks } from 'test-custom-types' +import { root, rpcUrl, signer } from './util.js' +import { Client, networks } from 'test-custom-types' +import { Ok, Err } from '@stellar/stellar-sdk/lib/rust_types/index.js' const publicKey = root.keypair.publicKey(); -const contract = new Contract({ ...networks.standalone, rpcUrl, wallet }); +const contract = new Client({ + ...networks.standalone, + rpcUrl, + allowHttp: true, + publicKey: root.keypair.publicKey(), + ...signer, +}); test('hello', async t => { const { result } = await contract.hello({ hello: 'tests' }) @@ -12,7 +19,7 @@ test('hello', async t => { }) test('woid', async t => { - t.is((await contract.woid()).result, undefined) + t.is((await contract.woid()).result, null) }) test('u32_fail_on_even', async t => { @@ -26,16 +33,19 @@ test('u32_fail_on_even', async t => { ) }) -test('u32', async t => { - t.is((await contract.u32({ u32_: 1 })).result, 1) +test('u32_', async t => { + // @ts-expect-error "heck" crate's `to_lower_camel_case` mismatches our `toLowerCamelCase` in stellar-sdk! + t.is((await contract.u32_({ u32_: 1 })).result, 1) }) -test('i32', async t => { - t.is((await contract.i32({ i32_: 1 })).result, 1) +test('i32_', async t => { + // @ts-expect-error "heck" crate's `to_lower_camel_case` mismatches our `toLowerCamelCase` in stellar-sdk! + t.is((await contract.i32_({ i32_: 1 })).result, 1) }) -test('i64', async t => { - t.is((await contract.i64({ i64_: 1n })).result, 1n) +test('i64_', async t => { + // @ts-expect-error "heck" crate's `to_lower_camel_case` mismatches our `toLowerCamelCase` in stellar-sdk! + t.is((await contract.i64_({ i64_: 1n })).result, 1n) }) test("strukt_hel", async (t) => { diff --git a/cmd/crates/soroban-spec-typescript/ts-tests/src/test-deserialized-transaction.ts b/cmd/crates/soroban-spec-typescript/ts-tests/src/test-deserialized-transaction.ts index f6152d2c11..8ce2cb933c 100644 --- a/cmd/crates/soroban-spec-typescript/ts-tests/src/test-deserialized-transaction.ts +++ b/cmd/crates/soroban-spec-typescript/ts-tests/src/test-deserialized-transaction.ts @@ -1,8 +1,14 @@ import test from "ava" -import { wallet, rpcUrl } from "./util.js" -import { Contract, networks } from "test-hello-world" +import { rpcUrl, root, signer } from "./util.js" +import { Client, networks } from "test-hello-world" -const contract = new Contract({ ...networks.standalone, rpcUrl, wallet }) +const contract = new Client({ + rpcUrl, + allowHttp: true, + publicKey: root.keypair.publicKey(), + ...signer, + ...networks.standalone, +}) test("has correctly-typed result", async (t) => { const initial = await contract.hello({ world: "tests" }) diff --git a/cmd/crates/soroban-spec-typescript/ts-tests/src/test-hello-world.ts b/cmd/crates/soroban-spec-typescript/ts-tests/src/test-hello-world.ts index e658c4552b..9fe15466a1 100644 --- a/cmd/crates/soroban-spec-typescript/ts-tests/src/test-hello-world.ts +++ b/cmd/crates/soroban-spec-typescript/ts-tests/src/test-hello-world.ts @@ -1,8 +1,14 @@ import test from "ava"; -import { root, wallet, rpcUrl } from "./util.js"; -import { Contract, networks } from "test-hello-world"; +import { root, signer, rpcUrl } from "./util.js"; +import { Client, networks } from "test-hello-world"; -const contract = new Contract({ ...networks.standalone, rpcUrl, wallet }); +const contract = new Client({ + ...networks.standalone, + rpcUrl, + allowHttp: true, + publicKey: root.keypair.publicKey(), + ...signer, +}) test("hello", async (t) => { t.deepEqual((await contract.hello({ world: "tests" })).result, ["Hello", "tests"]); diff --git a/cmd/crates/soroban-spec-typescript/ts-tests/src/test-methods-as-args.ts b/cmd/crates/soroban-spec-typescript/ts-tests/src/test-methods-as-args.ts index afa3b65124..ed805b4c97 100644 --- a/cmd/crates/soroban-spec-typescript/ts-tests/src/test-methods-as-args.ts +++ b/cmd/crates/soroban-spec-typescript/ts-tests/src/test-methods-as-args.ts @@ -1,8 +1,14 @@ import test from "ava"; -import { wallet, rpcUrl } from "./util.js"; -import { Contract, networks } from "test-hello-world"; +import { rpcUrl, root, signer } from "./util.js"; +import { Client, networks } from "test-hello-world"; -const contract = new Contract({ ...networks.standalone, rpcUrl, wallet }); +const contract = new Client({ + ...networks.standalone, + rpcUrl, + allowHttp: true, + publicKey: root.keypair.publicKey(), + ...signer, +}) // this test checks that apps can pass methods as arguments to other methods and have them still work const hello = contract.hello diff --git a/cmd/crates/soroban-spec-typescript/ts-tests/src/test-swap.ts b/cmd/crates/soroban-spec-typescript/ts-tests/src/test-swap.ts index a473cb4d88..57061d78d2 100644 --- a/cmd/crates/soroban-spec-typescript/ts-tests/src/test-swap.ts +++ b/cmd/crates/soroban-spec-typescript/ts-tests/src/test-swap.ts @@ -1,8 +1,8 @@ import test from "ava" import { SorobanRpc, xdr } from '@stellar/stellar-sdk' -import { wallet, rpcUrl, alice, bob, networkPassphrase, root, Wallet } from "./util.js" -import { Contract as Token } from "token" -import { Contract as Swap, networks, NeedsMoreSignaturesError } from "test-swap" +import { signer, rpcUrl, alice, bob, networkPassphrase, root } from "./util.js" +import { Client as Token } from "token" +import { basicNodeSigner, AssembledTransaction, Client as Swap, networks } from "test-swap" import fs from "node:fs" const tokenAId = fs.readFileSync(new URL("../contract-id-token-a.txt", import.meta.url), "utf8").trim() @@ -13,19 +13,25 @@ const tokenA = new Token({ contractId: tokenAId, networkPassphrase, rpcUrl, - wallet, + allowHttp: true, + publicKey: root.keypair.publicKey(), + ...signer, }) const tokenB = new Token({ contractId: tokenBId, networkPassphrase, rpcUrl, - wallet, + allowHttp: true, + publicKey: root.keypair.publicKey(), + ...signer, }) function swapContractAs(invoker: typeof root | typeof alice | typeof bob) { return new Swap({ ...networks.standalone, rpcUrl, - wallet: new Wallet(invoker.keypair.publicKey()), + allowHttp: true, + publicKey: invoker.keypair.publicKey(), + ...basicNodeSigner(invoker.keypair, networkPassphrase), }) } @@ -47,7 +53,7 @@ test('calling `signAndSend()` too soon throws descriptive error', async t => { min_b_for_a: amountBToSwap, }) const error = await t.throwsAsync(tx.signAndSend()) - t.true(error instanceof NeedsMoreSignaturesError, `error is not of type 'NeedsMoreSignaturesError'; instead it is of type '${error?.constructor.name}'`) + t.true(error instanceof AssembledTransaction.Errors.NeedsMoreSignatures, `error is not of type 'NeedsMoreSignaturesError'; instead it is of type '${error?.constructor.name}'`) if (error) t.regex(error.message, /needsNonInvokerSigningBy/) }) diff --git a/cmd/crates/soroban-spec-typescript/ts-tests/src/util.ts b/cmd/crates/soroban-spec-typescript/ts-tests/src/util.ts index d5539fd120..f5b6fbb8b0 100644 --- a/cmd/crates/soroban-spec-typescript/ts-tests/src/util.ts +++ b/cmd/crates/soroban-spec-typescript/ts-tests/src/util.ts @@ -1,6 +1,6 @@ import { spawnSync } from "node:child_process"; -import { Keypair, TransactionBuilder, hash } from "@stellar/stellar-sdk"; -import { Address } from 'test-custom-types' +import { Address, Keypair } from "@stellar/stellar-sdk"; +import { basicNodeSigner } from "@stellar/stellar-sdk/lib/contract_client/index.js"; const rootKeypair = Keypair.fromSecret(spawnSync("./soroban", ["keys", "show", "root"], { shell: true, encoding: "utf8" }).stdout.trim()); const aliceKeypair = Keypair.fromSecret(spawnSync("./soroban", ["keys", "show", "alice"], { shell: true, encoding: "utf8" }).stdout.trim()); @@ -21,37 +21,7 @@ export const bob = { address: Address.fromString(bobKeypair.publicKey()), } -function getKeypair(pk: string): Keypair { - return Keypair.fromSecret({ - [root.keypair.publicKey()]: root.keypair.secret(), - [alice.keypair.publicKey()]: alice.keypair.secret(), - [bob.keypair.publicKey()]: bob.keypair.secret(), - }[pk]) -} - export const rpcUrl = process.env.SOROBAN_RPC_URL ?? "http://localhost:8000/"; export const networkPassphrase = process.env.SOROBAN_NETWORK_PASSPHRASE ?? "Standalone Network ; February 2017"; -export class Wallet { - constructor(private publicKey: string) {} - isConnected = () => Promise.resolve(true) - isAllowed = () => Promise.resolve(true) - getUserInfo = () => Promise.resolve({ publicKey: this.publicKey }) - signTransaction = async (tx: string) => { - const t = TransactionBuilder.fromXDR(tx, networkPassphrase); - t.sign(getKeypair(this.publicKey)); - return t.toXDR(); - } - signAuthEntry = async ( - entryXdr: string, - opts?: { - accountToSign?: string, - } - ): Promise => { - return getKeypair(opts?.accountToSign ?? this.publicKey) - .sign(hash(Buffer.from(entryXdr, "base64"))) - .toString('base64') - } -} - -export const wallet = new Wallet(root.keypair.publicKey()) +export const signer = basicNodeSigner(root.keypair, networkPassphrase); diff --git a/cmd/soroban-cli/Cargo.toml b/cmd/soroban-cli/Cargo.toml index f5ef2b1b01..3601921adb 100644 --- a/cmd/soroban-cli/Cargo.toml +++ b/cmd/soroban-cli/Cargo.toml @@ -88,7 +88,7 @@ ethnum = { workspace = true } clap-markdown = { version = "0.1.3", optional = true } which = { workspace = true, features = ["regex"] } strsim = "0.10.0" -heck = "0.4.1" +heck = "0.5.0" tracing = { workspace = true } tracing-appender = { workspace = true } tracing-subscriber = { workspace = true, features = ["env-filter"] }