@polkadot/api/types#SignerOptions TypeScript Examples
The following examples show how to use
@polkadot/api/types#SignerOptions.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Transaction.ts From gear-js with GNU General Public License v3.0 | 6 votes |
public async signAndSend(
account: AddressOrPair,
optionsOrCallback?: Partial<SignerOptions> | TransactionStatusCb,
optionalCallback?: TransactionStatusCb,
): Promise<Hash | (() => void)> {
const [options, callback] = isFunction(optionsOrCallback)
? [undefined, optionsOrCallback]
: [optionsOrCallback, optionalCallback];
try {
return await this.submitted.signAndSend(account, options, callback);
} catch (error) {
const errorCode = +error.message.split(':')[0];
if (errorCode === 1010) {
throw new TransactionError('Account balance too low');
} else {
throw new TransactionError(error.message);
}
}
}
Example #2
Source File: Transaction.ts From gear-js with GNU General Public License v3.0 | 6 votes |
/**
*
* @param account
* @param options
* @example
* ```javascript
* const api = await GearApi.create();
* api.program.submit({code, gasLimit});
* // same for api.message, api.reply and others
* const paymentInfo = await api.program.paymentInfo(alice);
* const transactionFee = paymentInfo.partialFee.toNumber();
* consolg.log(transactionFee);
* ```
*/
paymentInfo(account: AddressOrPair, options?: SignerOptions): Promise<RuntimeDispatchInfo> {
return this.submitted.paymentInfo(account, options);
}
Example #3
Source File: Transaction.ts From gear-js with GNU General Public License v3.0 | 5 votes |
signAndSend(account: AddressOrPair, options?: Partial<SignerOptions>): Promise<Hash>;
Example #4
Source File: Transaction.ts From gear-js with GNU General Public License v3.0 | 5 votes |
signAndSend(
account: AddressOrPair,
options: Partial<SignerOptions>,
callback: TransactionStatusCb,
): Promise<() => void>;
Example #5
Source File: useApiCalls.ts From parity-bridges-ui with GNU General Public License v3.0 | 4 votes |
useApiCalls = (): ApiCallsContextType => {
const { sourceChainDetails, targetChainDetails } = useSourceTarget();
const {
apiConnection: { api: sourceApi },
chain: sourceChain
} = sourceChainDetails;
const { keyringPairs, keyringPairsReady } = useKeyringContext();
const { getValuesByChain } = useChainGetters();
const createType = useCallback(
(chain, type, data) => {
const { api } = getValuesByChain(chain);
return api.registry.createType(type, data);
},
[getValuesByChain]
);
const stateCall = useCallback(
(chain: string, methodName: string | Text, data: string | Uint8Array | Bytes, at) => {
const { api } = getValuesByChain(chain);
const params: [string | Text, string | Uint8Array | Bytes] = [methodName, data];
if (at) {
params.push(at);
}
return api.rpc.state.call<Codec>(...params);
},
[getValuesByChain]
);
const internalTransfer = useCallback(
async (dispatchers, transfersData) => {
const { dispatchTransaction, dispatchMessage } = dispatchers;
const { receiverAddress, transferAmount, account } = transfersData;
const type = TransactionTypes.INTERNAL_TRANSFER;
const id = Date.now().toString();
dispatchTransaction(TransactionActionCreators.setTransactionRunning(true));
try {
const transfer = sourceApi.tx.balances.transfer(receiverAddress, transferAmount);
const options: Partial<SignerOptions> = {
nonce: -1
};
let sourceAccount: string | KeyringPair = account;
if (account.meta.isInjected) {
const injector = await web3FromSource(account.meta.source as string);
options.signer = injector.signer;
sourceAccount = account.address;
}
const transactionDisplayPayload = {
sourceAccount: account?.address || sourceAccount,
transferAmount: transferAmount.toNumber(),
receiverAddress
};
const unsub = await transfer.signAndSend(sourceAccount, { ...options }, async ({ status }) => {
const steps = createEmptyInternalSteps(sourceChain);
if (status.isReady) {
dispatchTransaction(
TransactionActionCreators.createTransactionStatus({
block: null,
blockHash: null,
deliveryBlock: null,
id,
input: transferAmount,
messageNonce: null,
receiverAddress,
sourceAccount: account.address,
senderName: getName(account),
sourceChain,
status: TransactionStatusEnum.IN_PROGRESS,
targetChain: '',
type,
transactionDisplayPayload,
payloadHex: transfer.toHex(),
steps
})
);
}
if (status.isBroadcast) {
dispatchMessage(MessageActionsCreators.triggerInfoMessage({ message: 'Transaction was broadcasted' }));
dispatchTransaction(TransactionActionCreators.reset());
}
if (status.isInBlock) {
try {
const res = (await sourceApi.rpc.chain.getBlock(status.asInBlock)) as SignedBlock;
const block = res.block.header.number.toString();
dispatchTransaction(
TransactionActionCreators.updateTransactionStatus(
{
block,
blockHash: status.asInBlock.toString()
},
id
)
);
} catch (e) {
if (e instanceof Error) {
logger.error(e.message);
throw new Error('Issue reading block information.');
}
}
}
if (status.isFinalized) {
dispatchTransaction(
TransactionActionCreators.updateTransactionStatus(
{
status: TransactionStatusEnum.FINALIZED
},
id
)
);
logger.info(`Transaction finalized at blockHash ${status.asFinalized}`);
unsub();
}
});
} catch (e) {
if (e instanceof Error) {
dispatchMessage(MessageActionsCreators.triggerErrorMessage({ message: e.message }));
logger.error(e.message);
}
} finally {
dispatchTransaction(TransactionActionCreators.setTransactionRunning(false));
}
},
[sourceApi.rpc.chain, sourceApi.tx.balances, sourceChain]
);
const updateSenderAccountsInformation = useCallback(
async (dispatchAccount) => {
const formatBalanceAddress = (data: any, api: ApiPromise): BalanceState => {
return {
chainTokens: data.registry.chainTokens[0],
formattedBalance: formatBalance(data.free, {
decimals: api.registry.chainDecimals[0],
withUnit: api.registry.chainTokens[0],
withSi: true
}),
free: data.free
};
};
if (!keyringPairsReady || !keyringPairs.length) {
return {};
}
const getAccountInformation = async (sourceRole: any, targetRole: any) => {
const {
apiConnection: { api: sourceApi },
chain: sourceChain,
configs: sourceConfigs
} = sourceRole;
const {
apiConnection: { api: targetApi },
configs: targetConfigs
} = targetRole;
const accounts = await Promise.all(
keyringPairs.map(async ({ address, meta }) => {
const sourceAddress = encodeAddress(address, sourceConfigs.ss58Format);
const toDerive = {
ss58Format: targetConfigs.ss58Format,
address: sourceAddress || '',
bridgeId: getBridgeId(targetApi, sourceChain)
};
const { data } = await sourceApi.query.system.account(sourceAddress);
const sourceBalance = formatBalanceAddress(data, sourceApi);
const companionAddress = getDeriveAccount(toDerive);
const { data: dataCompanion } = await targetApi.query.system.account(companionAddress);
const targetBalance = formatBalanceAddress(dataCompanion, targetApi);
const name = (meta.name as string).toLocaleUpperCase();
return {
account: { address: sourceAddress, balance: sourceBalance, name },
companionAccount: { address: companionAddress, balance: targetBalance, name }
};
})
);
return accounts;
};
const sourceAddresses = await getAccountInformation(sourceChainDetails, targetChainDetails);
const targetAddresses = await getAccountInformation(targetChainDetails, sourceChainDetails);
dispatchAccount(
AccountActionCreators.setDisplaySenderAccounts({
[sourceChainDetails.chain]: sourceAddresses,
[targetChainDetails.chain]: targetAddresses
})
);
},
[keyringPairs, keyringPairsReady, sourceChainDetails, targetChainDetails]
);
return { createType, stateCall, internalTransfer, updateSenderAccountsInformation };
}
Example #6
Source File: useSendMessage.ts From parity-bridges-ui with GNU General Public License v3.0 | 4 votes |
function useSendMessage({ input, type }: Props) {
const { estimatedSourceFee, receiverAddress, payload, transferAmount } = useTransactionContext();
const { dispatchTransaction } = useUpdateTransactionContext();
const laneId = useLaneId();
const sourceTargetDetails = useSourceTarget();
const {
sourceChainDetails: {
apiConnection: { api: sourceApi },
chain: sourceChain
},
targetChainDetails: {
chain: targetChain,
apiConnection: { api: targetApi }
}
} = sourceTargetDetails;
const { account, companionAccount } = useAccountContext();
const { createType } = useApiCalls();
const { dispatchMessage } = useUpdateMessageContext();
const makeCall = useCallback(
async (id: string) => {
try {
if (!account || !payload) {
return;
}
const payloadType = createType(sourceChain as keyof InterfaceTypes, 'OutboundPayload', payload);
const payloadHex = payloadType.toHex();
const { bridgedMessages } = getSubstrateDynamicNames(targetChain);
const bridgeMessage = sourceApi.tx[bridgedMessages].sendMessage(laneId, payload, estimatedSourceFee);
logger.info(`bridge::sendMessage ${bridgeMessage.toHex()}`);
const options: Partial<SignerOptions> = {
nonce: -1
};
let sourceAccount: string | KeyringPair = account;
if (account.meta.isInjected) {
const injector = await web3FromSource(account.meta.source as string);
options.signer = injector.signer;
sourceAccount = account.address;
}
const { transactionDisplayPayload } = getTransactionDisplayPayload({
payload,
account: account.address,
createType,
sourceTargetDetails
});
const formattedTransferAmount = getFormattedAmount(targetApi, transferAmount, type);
const signed = await bridgeMessage.signAsync(sourceAccount, { ...options });
dispatchTransaction(TransactionActionCreators.setTransactionToBeExecuted(false));
dispatchTransaction(TransactionActionCreators.setTransactionRunning(true));
const unsub = await signed.send(({ events = [], status }) => {
if (status.isReady) {
dispatchTransaction(
TransactionActionCreators.createTransactionStatus({
block: null,
blockHash: null,
id,
input,
messageNonce: null,
receiverAddress,
sourceAccount: account.address,
senderName: getName(account),
companionAccount,
sourceChain,
transferAmount: formattedTransferAmount,
status: TransactionStatusEnum.CREATED,
targetChain,
type,
payloadHex,
transactionDisplayPayload,
deliveryBlock: null,
steps: createEmptySteps(sourceChain, targetChain)
})
);
}
if (status.isBroadcast) {
dispatchMessage(MessageActionsCreators.triggerInfoMessage({ message: 'Transaction was broadcasted' }));
dispatchTransaction(TransactionActionCreators.reset());
}
if (status.isInBlock) {
dispatchTransaction(TransactionActionCreators.setTransactionRunning(false));
events.forEach(({ event: { data, method } }) => {
if (method.toString() === 'MessageAccepted') {
const messageNonce = data.toArray()[1].toString();
(sourceApi.rpc.chain.getBlock(status.asInBlock) as Promise<SignedBlock>)
.then((res) => {
const block = res.block.header.number.toString();
dispatchTransaction(
TransactionActionCreators.updateTransactionStatus(
{
block,
blockHash: status.asInBlock.toString(),
messageNonce,
status: TransactionStatusEnum.IN_PROGRESS
},
id
)
);
})
.catch((e) => {
logger.error(e.message);
throw new Error('Issue reading block information.');
});
}
});
}
if (status.isFinalized) {
logger.info(`Transaction finalized at blockHash ${status.asFinalized}`);
unsub();
}
});
} catch (e) {
if (e instanceof Error) {
logger.error(e.message);
if (e.message === TX_CANCELLED) {
dispatchTransaction(TransactionActionCreators.enableTxButton());
dispatchTransaction(TransactionActionCreators.setTransactionToBeExecuted(false));
dispatchTransaction(TransactionActionCreators.setTransactionRunning(false));
return dispatchMessage(
MessageActionsCreators.triggerErrorMessage({ message: 'Transaction was cancelled from the extension.' })
);
}
dispatchMessage(MessageActionsCreators.triggerErrorMessage({ message: e.message }));
}
} finally {
dispatchTransaction(TransactionActionCreators.setTransactionToBeExecuted(false));
}
},
[
account,
companionAccount,
createType,
dispatchMessage,
dispatchTransaction,
estimatedSourceFee,
input,
laneId,
payload,
receiverAddress,
sourceApi.rpc.chain,
sourceApi.tx,
sourceChain,
sourceTargetDetails,
targetApi,
targetChain,
transferAmount,
type
]
);
const sendLaneMessage = useCallback(() => {
const id = Date.now().toString();
dispatchTransaction(TransactionActionCreators.setTransactionToBeExecuted(true));
return makeCall(id);
}, [dispatchTransaction, makeCall]);
return sendLaneMessage;
}