@polkadot/types/interfaces#SignedBlock TypeScript Examples
The following examples show how to use
@polkadot/types/interfaces#SignedBlock.
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: functions.ts From community-repo with GNU General Public License v3.0 | 6 votes |
export async function getChangeAction(api: ApiPromise, method: string, blockHeight:number, blockHash:Hash, eventIndex: number, event: EventRecord): Promise<ActionData|null> {
const getBlock = await api.rpc.chain.getBlock(blockHash) as SignedBlock
const extrinsics = getBlock.block.extrinsics as Vec<Extrinsic>
for (let n=0; n<extrinsics.length; n++) {
const extSection = extrinsics[n].method.section
const extMethod = extrinsics[n].method.method
let extrinscIndex = 0
console.log(`Extrinsics section=${extSection}, Event method=${extMethod}`)
if (extSection == "content" && extMethod == method) {
extrinscIndex +=1
if (eventIndex == extrinscIndex) {
const extrinsic = extrinsics[n]
const actor = extrinsic.args[0] as Actor
const ent = event.event.data[1]
let entityId:number = +(ent.toString())
const video:ActionData = {
blockHeight,
action: method,
entityId,
signer: extrinsic.signer.toString(),
actor: actor.toHuman()
}
return video
}
}
}
return null
}
Example #2
Source File: ByHash.tsx From crust-apps with Apache License 2.0 | 6 votes |
function transformResult ([events, getBlock, getHeader]: [EventRecord[], SignedBlock, HeaderExtended?]): [KeyedEvent[], SignedBlock, HeaderExtended?] {
return [
events.map((record, index) => ({
indexes: [index],
key: `${Date.now()}-${index}-${record.hash.toHex()}`,
record
})),
getBlock,
getHeader
];
}
Example #3
Source File: Blocks.ts From gear-js with GNU General Public License v3.0 | 6 votes |
/**
* Get data of particular block by blockNumber or blockHash
* @param hashOrNumber
* @returns
*/
async get(hashOrNumber: `0x${string}` | Uint8Array | number): Promise<SignedBlock> {
const hash = isU8a(hashOrNumber) || isHex(hashOrNumber) ? hashOrNumber : await this.getBlockHash(+hashOrNumber);
try {
return await this.api.rpc.chain.getBlock(hash);
} catch (error) {
throw new GetBlockError(error.message, hash);
}
}
Example #4
Source File: index.ts From parity-bridges-ui with GNU General Public License v3.0 | 6 votes |
checkMessageDispatchedEvent = async (
targetApi: ApiPromise,
blockNumber: string | null,
messageNonce: string | null
) => {
if (!blockNumber || !messageNonce) {
return TransactionStatusEnum.IN_PROGRESS;
}
const blockHash = (await targetApi.rpc.chain.getBlockHash(blockNumber)) as BlockHash;
const signedBlock = (await targetApi.rpc.chain.getBlock(blockHash)) as SignedBlock;
const allRecords = (await targetApi.query.system.events.at(signedBlock.block.header.hash)) as Vec<any>;
let status = TransactionStatusEnum.FAILED;
signedBlock.block.extrinsics.forEach((ext, index) => {
const events = allRecords.filter(({ phase }) => phase.isApplyExtrinsic && phase.asApplyExtrinsic.eq(index));
const found = events.find(({ event: { method, data } }) => {
return method === MESSAGE_DISPATCH_EVENT && deepFind(data, messageNonce) && deepFind(data, OK);
});
if (found) {
status = TransactionStatusEnum.COMPLETED;
}
});
return status;
}
Example #5
Source File: SubstrateService.ts From squid with GNU General Public License v3.0 | 6 votes |
async getBlockData(hash: Hash): Promise<BlockData> {
const data = {
events: this.eventsAt(hash),
signedBlock: this.getSignedBlock(hash),
lastUpgrade: this.lastRuntimeUpgrade(hash),
runtimeVersion: this.runtimeVersion(hash),
validatorId: this.validatorId(hash),
}
const out = (await pProps(data)) as Partial<BlockData>
if (getConfig().VERBOSE) debug(`Out: ${JSON.stringify(out, null, 2)}`)
out.timestamp = getBlockTimestamp(
(out.signedBlock as SignedBlock).block.extrinsics.toArray()
)
return out as BlockData
}
Example #6
Source File: general.ts From community-repo with GNU General Public License v3.0 | 5 votes |
async function main() {
// Initialise the provider to connect to the local node
const provider = new WsProvider('ws://127.0.0.1:9944');
//If you want to play around on our staging network, go ahead and connect to this staging network instead.
//const provider = new WsProvider('wss://testnet-rpc-2-singapore.joystream.org');
// Create the API and wait until ready
const api = await ApiPromise.create({ provider, types })
// get finalized head of chain, as number and hash:
const finalizedHeadNumber = await api.derive.chain.bestNumberFinalized()
const finalizedHeadHash = await api.rpc.chain.getFinalizedHead()
// get head of chain, as hash or number:
const headNumber = await api.derive.chain.bestNumber()
const headHash = await api.rpc.chain.getBlockHash(headNumber)
console.log(
`Finalized head of chain
- as number: ${finalizedHeadNumber}
- with hash: ${finalizedHeadHash}`
)
console.log(
`Head of chain
- as number: ${headNumber}
- with hash: ${headHash}`
)
// get current issuance
const issuance = await api.query.balances.totalIssuance() as Balance
console.log(`current issuance is: ${issuance.toNumber()}tJOY`)
// get events in newest block:
const events = await api.query.system.events() as Vec<EventRecord>;
for (let { event } of events) {
const section = event.section
const method = event.method
const data = event.data
console.log("section",section)
console.log("method",method)
console.log("data",data.toHuman())
console.log("")
}
// get extrinsics in finalized head block:
const getLatestBlock = await api.rpc.chain.getBlock(finalizedHeadHash) as SignedBlock
const extrinsics = getLatestBlock.block.extrinsics as Vec<Extrinsic>
for (let i=0; i<extrinsics.length; i++) {
const section = extrinsics[i].method.section
const method = extrinsics[i].method.method
console.log("section",section)
console.log("method",method)
console.log("")
// get signer of extrinsics if applicable
const signer = extrinsics[i].signer
if (!signer.isEmpty) {
console.log("signer",signer)
}
}
api.disconnect()
}
Example #7
Source File: get-events-and-extrinsics.ts From community-repo with GNU General Public License v3.0 | 5 votes |
async function main() {
// Initialise the provider to connect to the local node
const provider = new WsProvider('ws://127.0.0.1:9944');
//If you want to play around on our staging network, go ahead and connect to this staging network instead.
//const provider = new WsProvider('wss://testnet-rpc-2-singapore.joystream.org');
// Create the API and wait until ready
const api = await ApiPromise.create({ provider, types })
// get all extrinsic and event types in a range of blocks (only works for last 200 blocks unless you are querying an archival node)
// will take a loooong time if you check too many blocks :)
const firstBlock = 800000
const lastBlock = 801000
const eventTypes:string[] = []
const extrinsicTypes: string[] = []
for (let blockHeight=firstBlock; blockHeight<lastBlock; blockHeight++) {
const blockHash = await api.rpc.chain.getBlockHash(blockHeight)
const events = await api.query.system.events.at(blockHash) as Vec<EventRecord>;
const getBlock = await api.rpc.chain.getBlock(blockHash) as SignedBlock
const extrinsics = getBlock.block.extrinsics as Vec<Extrinsic>
for (let { event } of events) {
const section = event.section
const method = event.method
const eventType = section+`:`+method
if (!eventTypes.includes(eventType)) {
eventTypes.push(eventType)
}
}
for (let i=0; i<extrinsics.length; i++) {
const section = extrinsics[i].method.section
const method = extrinsics[i].method.method
const extrinsicType = section+`:`+method
if (!extrinsicTypes.includes(extrinsicType)) {
extrinsicTypes.push(extrinsicType)
}
}
}
console.log("number of unique event types in range:",eventTypes.length)
console.log("list of the unique event types in range:")
console.log(JSON.stringify(eventTypes, null, 4))
console.log("")
console.log("number of unique extrinsic types in range",extrinsicTypes.length)
console.log("list of the unique extrinsic types in range:")
console.log(JSON.stringify(extrinsicTypes, null, 4))
api.disconnect()
}
Example #8
Source File: mintingAndBurning.ts From community-repo with GNU General Public License v3.0 | 5 votes |
filterBlockExtrinsicsByMethod = (block: SignedBlock, name: string) =>
block.block.extrinsics.filter(
({ method: { method, section } }) => `${section}.${method}` === name
)
Example #9
Source File: mintingAndBurning.ts From community-repo with GNU General Public License v3.0 | 5 votes |
filterBlockExtrinsicsByMethods = (block: SignedBlock, names: string[]) =>
block.block.extrinsics.filter(
({ method: { method, section } }) =>
names.indexOf(`${section}.${method}`) >= 0
)
Example #10
Source File: Blocks.ts From gear-js with GNU General Public License v3.0 | 5 votes |
/**
* Get data of particular block by blockHash
* @param hash
* @returns
*/
async get(hash: `0x${string}` | Uint8Array): Promise<SignedBlock>;
Example #11
Source File: Blocks.ts From gear-js with GNU General Public License v3.0 | 5 votes |
/**
* Get data of particular block by blockNumber
* @param number
* @returns
*/
async get(number: number): Promise<SignedBlock>;
Example #12
Source File: Blocks.ts From gear-js with GNU General Public License v3.0 | 5 votes |
/**
* Get data of particular block by blockNumber or blockHash
* @param hashOrNumber
* @returns
*/
async get(hashOrNumber: `0x${string}` | Uint8Array | number): Promise<SignedBlock>;
Example #13
Source File: SubstrateService.ts From squid with GNU General Public License v3.0 | 5 votes |
async getSignedBlock(hash: Hash | Uint8Array | string): Promise<SignedBlock> {
debug(`Fething signed block: ${JSON.stringify(hash)}`)
return this.apiCall(
(api) => api.rpc.chain.getBlock(hash),
`get signed block by hash ${JSON.stringify(hash)}`
)
}
Example #14
Source File: ByHash.tsx From crust-apps with Apache License 2.0 | 4 votes |
function BlockByHash ({ className = '', error, value }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const mountedRef = useIsMountedRef();
const [[events, getBlock, getHeader], setState] = useState<[KeyedEvent[]?, SignedBlock?, HeaderExtended?]>([]);
const [myError, setError] = useState<Error | null | undefined>(error);
useEffect((): void => {
value && Promise
.all([
api.query.system.events.at(value),
api.rpc.chain.getBlock(value),
api.derive.chain.getHeader(value)
])
.then((result): void => {
mountedRef.current && setState(transformResult(result));
})
.catch((error: Error): void => {
mountedRef.current && setError(error);
});
}, [api, mountedRef, value]);
const blockNumber = getHeader?.number.unwrap();
const parentHash = getHeader?.parentHash.toHex();
const hasParent = !getHeader?.parentHash.isEmpty;
return (
<div className={className}>
<Table
header={
getHeader
? [
[formatNumber(blockNumber), 'start', 1],
[t('hash'), 'start'],
[t('parent'), 'start'],
[t('extrinsics'), 'start'],
[t('state'), 'start'],
[]
]
: [['...', 'start', 6]]
}
isFixed
>
{myError
? <tr><td colSpan={6}>{t('Unable to retrieve the specified block details. {{error}}', { replace: { error: myError.message } })}</td></tr>
: getBlock && !getBlock.isEmpty && getHeader && !getHeader.isEmpty && (
<tr>
<td className='address'>
{getHeader.author && (
<AddressSmall value={getHeader.author} />
)}
</td>
<td className='hash overflow'>{getHeader.hash.toHex()}</td>
<td className='hash overflow'>{
hasParent
? <Link to={`/explorer/query/${parentHash || ''}`}>{parentHash}</Link>
: parentHash
}</td>
<td className='hash overflow'>{getHeader.extrinsicsRoot.toHex()}</td>
<td className='hash overflow'>{getHeader.stateRoot.toHex()}</td>
<td>
<LinkExternal
data={value}
type='block'
/>
</td>
</tr>
)
}
</Table>
{getBlock && getHeader && (
<>
<Extrinsics
blockNumber={blockNumber}
events={events}
value={getBlock.block.extrinsics}
/>
<Columar>
<Columar.Column>
<Events
eventClassName='explorer--BlockByHash-block'
events={events?.filter(({ record: { phase } }) => !phase.isApplyExtrinsic)}
label={t<string>('system events')}
/>
</Columar.Column>
<Columar.Column>
<Logs value={getHeader.digest.logs} />
<Justifications value={getBlock.justifications} />
</Columar.Column>
</Columar>
</>
)}
</div>
);
}
Example #15
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 #16
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;
}