@@ -10,8 +10,9 @@ import {
1010} from 'dedot/contracts' ;
1111import { ISubmittableResult } from 'dedot/types' ;
1212import { assert , deferred } from 'dedot/utils' ;
13- import { TypinkError } from '../utils/index.js' ;
13+ import { BalanceInsufficientError , ContractMessageError } from '../utils/index.js' ;
1414import { useDeepDeps } from './internal/index.js' ;
15+ import { ISubstrateClient } from 'dedot' ;
1516
1617type UseContractTx < A extends GenericContractApi = GenericContractApi > = OmitNever < {
1718 [ K in keyof A [ 'tx' ] ] : K extends string ? ( K extends `${infer Literal } ` ? Literal : never ) : never ;
@@ -63,8 +64,8 @@ export function useContractTx<
6364 const signAndSend = useMemo (
6465 ( ) => {
6566 return async ( o : Parameters < UseContractTxReturnType < T > [ 'signAndSend' ] > [ 0 ] ) => {
66- assert ( contract , 'Contract Not Found ' ) ;
67- assert ( connectedAccount , 'Connected Account Not Found ' ) ;
67+ assert ( contract , 'Contract not found ' ) ;
68+ assert ( connectedAccount , 'No connected account. Please connect your wallet. ' ) ;
6869
6970 setInProgress ( true ) ;
7071 setInBestBlockProgress ( true ) ;
@@ -122,18 +123,15 @@ export async function contractTx<
122123 callback ?: ( result : ISubmittableResult ) => void ;
123124 } & Args < Pop < Parameters < T [ 'tx' ] [ M ] > > > ,
124125) : Promise < void > {
125- // TODO assertions
126- // TODO check if balance is sufficient
127-
128126 const defer = deferred < void > ( ) ;
129127
130128 const signAndSend = async ( ) => {
131129 const { contract, fn, args = [ ] , caller, txOptions = { } , callback } = parameters ;
132130
131+ await checkBalanceSufficient ( contract . client , caller ) ;
132+
133133 try {
134- // TODO dry running
135134 const dryRunOptions : ContractCallOptions = { caller } ;
136-
137135 const dryRun = await contract . query [ fn ] ( ...args , dryRunOptions ) ;
138136 console . log ( 'Dry run result:' , dryRun ) ;
139137
@@ -143,8 +141,7 @@ export async function contractTx<
143141 } = dryRun ;
144142
145143 if ( data && data [ 'isErr' ] && data [ 'err' ] ) {
146- // TODO Add a specific contract level error
147- throw new TypinkError ( JSON . stringify ( data [ 'err' ] ) ) ;
144+ throw new ContractMessageError ( data [ 'err' ] ) ;
148145 }
149146
150147 const actualTxOptions : ContractTxOptions = {
@@ -179,3 +176,14 @@ export async function contractTx<
179176
180177 return defer . promise ;
181178}
179+
180+ const checkBalanceSufficient = async < T extends GenericContractApi = GenericContractApi > (
181+ client : ISubstrateClient < T [ 'types' ] [ 'ChainApi' ] > ,
182+ caller : string ,
183+ ) : Promise < void > => {
184+ const balance = await client . query . system . account ( caller ) ;
185+ // TODO better calculate reducible balance
186+ if ( balance . data . free <= 0n ) {
187+ throw new BalanceInsufficientError ( caller ) ;
188+ }
189+ } ;
0 commit comments