diff --git a/docs/sdk/darwinia.js/Substrate API/Constants.md b/docs/sdk/darwinia.js/Substrate API/Constants.md new file mode 100644 index 00000000..ad1dd687 --- /dev/null +++ b/docs/sdk/darwinia.js/Substrate API/Constants.md @@ -0,0 +1,275 @@ +--- +sidebar_position: 3 +--- + +# Constants + + + + +The following sections contain the module constants, also known as parameter types. These can only be changed as part of a runtime upgrade. On the api, these are exposed via api.consts.``.``. + +(NOTE: These were generated from a static/snapshot view of a recent Darwinia master node. Some items may not be available in older nodes, or in any customized implementations.) + + +- [bridgeCrabGrandpa](#bridgeCrabGrandpa) +- [bridgeCrabMessages](#bridgeCrabMessages) +- [feeMarket](#feeMarket) +- [ktonTreasury](#ktonTreasury) +- [phragmenElection](#phragmenElection) + +- [tronBacking](#tronBacking) + + + + +*** + +bridgeCrabGrandpa +

+ + headersToKeep: u32 + + - **interface**: `api.consts.bridgeCrabGrandpa.headersToKeep`

+ + + - **summary**: Maximal number of finalized headers to keep in the storage.

+ + The setting is there to prevent growing the on-chain state indefinitely. Notethe setting does not relate to block numbers - we will simply keep as much items in the storage, so it doesn't guarantee any fixed timeframe for finality headers. + + + maxRequests: u32 + + - **interface**: `api.consts.bridgeCrabGrandpa.maxRequests`

+ + - **summary**: The upper bound on the number of requests allowed by the pallet.

+ + Once this bound is reached the pallet will not allow any dispatchables to be called until the request count has decreased. + +bridgeCrabMessages +

+bridgedChainId: u8aFixed + + + + + - **interface**: `api.consts.bridgeCrabMessages.bridgedChainId`

+ + + - **summary**: Gets the chain id value from the instance.

+ + +feeMarket +

+ + +guardRelayersRewardRatio: Permill + + + - **interface**: `api.consts.feeMarket.guardRelayersRewardRatio`

+ + + - **summary**: Percentage of reward for assigned relayers on duty after a message is successfully delivered.

+ +assignedRelayerSlashRatio: Permill + + + - **interface**: `api.consts.feeMarket.assignedRelayerSlashRatio`

+ + + - **summary**: Assigned relayers collateral slash percentage after message delivery failure.

+ +messageRelayersRewardRatio: Permill + + + - **interface**: `api.consts.feeMarket.messageRelayersRewardRatio`

+ + - **summary**: The percentage of relayer that gets rewarded for delivering the message.

+ +confirmRelayersRewardRatio: Permill + + + - **interface**: `api.consts.feeMarket.confirmRelayersRewardRatio`

+ + - **summary**: The percentage of relayer that gets rewarded for confirming the message.

+ + +collateralPerOrder: u128 + + + - **interface**: `api.consts.feeMarket.collateralPerOrder`

+ + + - **summary**: The collateral relayer need to lock for each order.

+ + +minimumRelayFee: u128 + + + - **interface**: `api.consts.feeMarket.minimumRelayFee`

+ + + - **summary**: Minimum relay fee requirement for bridgers when they enroll the fee market.

+ + +slot: u32 + + + - **interface**: `api.consts.feeMarket.slot`

+ + + - **summary**: The slot times set.

+ + + +treasuryPalletId: FrameSupportPalletId + + + - **interface**: `api.consts.feeMarket.treasuryPalletId`

+ + + - **summary**: The treasury id.

+ +lockId: U8aFixed + + + - **interface**: `api.consts.feeMarket.lockId`

+ + - **summary**: The lock id for relayer's collateral.

+ + + + + +ktonTreasury +

+ +burn: Permill + + +- **interface**: `api.consts.ktonTreasury.burn`

+ +- **summary**: Percentage of spare funds (if any) that are burnt per spend period.

+ + + +maxApprovals: u32 + + +- **interface**: `api.consts.ktonTreasury.maxApprovals`

+ +- **summary**: The maximum number of approvals that can wait in the spending queue.

+ + + +palletId: FrameSupportPalletId + + +- **interface**: `api.consts.ktonTreasury.palletId`

+ +- **summary**: The treasury's pallet id, used for deriving its sovereign account ID.

+ + +proposalBond: Permill + + +- **interface**: `api.consts.ktonTreasury.proposalBond`

+ +- **summary**: Fraction of a proposal's value that should be bonded in order to place the proposal. An accepted proposal gets these back. A rejected proposal does not.

+ + + +proposalBondMinimum: u128 + + +- **interface**: `api.consts.ktonTreasury.proposalBondMinimum`

+ +- **summary**: Minimum amount of funds that should be placed in a deposit for making a proposal.

+ + +spendPeriod: u32 + + +- **interface**: `api.consts.ktonTreasury.spendPeriod`

+ +- **summary**: Period between successive spends.

+ + + + + +phragmenElection +

+ + + +candidacyBond: u128 + + +- **interface**: `api.consts.phragmenElection.candidacyBond`

+ +- **summary**: How much should be locked up in order to submit one's candidacy.

+ +desiredMembers: u32 + + +- **interface**: `api.consts.phragmenElection.desiredMembers`

+ +- **summary**: Number of members to elect.

+ + + + +desiredRunnersUp: u32 + + +- **interface**: `api.consts.phragmenElection.desiredRunnersUp`

+ +- **summary**: Number of runners_up to keep.

+ + + +votingBondBase: u128 + + +- **interface**: `api.consts.phragmenElection.votingBondBase`

+ +- **summary**: Base deposit associated with voting.

+ + This should be sensibly high to economically ensure the pallet cannot be attacked by creating a gigantic number of votes. + + +votingBondFactor: u128 + + +- **interface**: `api.consts.phragmenElection.votingBondFactor`

+ +- **summary**: The amount of bond that need to be locked for each vote (32 bytes).

+ + + + +tronBacking +

+ + +palletId: FrameSupportPalletId + + +- **interface**: `api.consts.tronBacking.palletId`

+ +- **summary**: The pallet id of this pallet.

+ + + + + + + + + + + + + + diff --git a/docs/sdk/darwinia.js/Substrate API/Extrinsics.md b/docs/sdk/darwinia.js/Substrate API/Extrinsics.md new file mode 100644 index 00000000..6fd907a9 --- /dev/null +++ b/docs/sdk/darwinia.js/Substrate API/Extrinsics.md @@ -0,0 +1,437 @@ +--- +sidebar_position: 4 +--- + +# Extrinsic + + + +The following sections contain Extrinsics methods which are part of the default Darwinia runtime. On the api, these are exposed via api.tx.``.``. + +(NOTE: These were generated from a static/snapshot view of a recent Darwinia master node. Some items may not be available in older nodes, or in any customized implementations.) + + + + +- [bridgeCrabGrandpa](#bridgeCrabGrandpa) +- [bridgeCrabMessages](#bridgeCrabMessages) +- [feeMarket](#feeMarket) +- [ktonTreasury](#ktonTreasury) +- [phragmenElection](#phragmenElection) +- [kton](#kton) + +*** + + +bridgeCrabGrandpa +

+ + + initialize(initData:BpHeaderChainInitializationData) + + + - **interface**: `api.tx.bridgeCrabGrandpa.initialize`

+ + + - **summary**: Bootstrap the bridge pallet with an initial header and authority set from which to sync.

+ + The initial configuration provided does not need to be the genesis header of the bridged chain, it can be any arbitrary header. You can also provide the next scheduled set change if it is already know. + + + + + setOperational(operational:boolean) + + + - **interface**: `api.tx.bridgeCrabGrandpa.setOperational`

+ + + - **summary**: Halt or resume all pallet operations, May only be called either by root, or by `PalletOwner`.

+ + + + setOwner(newOwner:AccountId32) + + + - **interface**: `api.tx.bridgeCrabGrandpa.setOwner`

+ + + - **summary**: Change `PalletOwner`.

+ + + +submitFinalityProof(finalityTarget:SpRuntimeHeader,justification: BpHeaderChainJustificationGrandpaJustification ) +

+ + - **interface**: `api.tx.bridgeCrabGrandpa.submitFinalityProof`

+ + + - **summary**: Verify a target header is finalized according to the given finality proof.

+ + It will use the underlying storage pallet to fetch information about the current + authorities and best finalized header in order to verify that the header is finalized. + + +bridgeCrabMessages +

+ + +increaseMessageFee(laneId:U8aFixed,nonce: u64, additionalFee:u128) + + + - **interface**: `api.tx.bridgeCrabMessages.increaseMessageFee`

+ + + - **summary**: Pay additional fee for the message.

+ + + + + receiveMessagesDeliveryProof(proof:BridgeRuntimeCommonMessagesSourceFromBridgedChainMessagesDeliveryProof,relayersState: BpMessagesUnrewardedRelayersState) + + + - **interface**: `api.tx.bridgeCrabMessages.receiveMessagesDeliveryProof`

+ + + - **summary**: Receive messages delivery proof from bridged chain.

+ + + +receiveMessagesProof(relayerIdAtBridgedChain:AccountId32,proof: BridgeRuntimeCommonMessagesTargetFromBridgedChainMessagesProof, messagesCount:u32, dispatchWeight:u64) + + + - **interface**: `api.tx.bridgeCrabMessages.receiveMessagesProof`

+ + + - **summary**: Receive messages proof from bridged chain.

+ + the weight of the call assumes that the transaction always brings outbound lane state update. Because of that, the submitter (relayer) has no benefit of not including this data in the transaction, so reward confirmations lags should be minimal. + + + +sendMessage(laneId:U8aFixed,payload: BpMessageDispatchMessagePayload, messagesCount:u32, deliveryAndDispatchFee:u128) + + + - **interface**: `api.tx.bridgeCrabMessages.sendMessage`

+ + + - **summary**: Send message over lane.

+ + + +setOperatingMode(operatingMode:BpMessagesOperatingMode) + + + - **interface**: `api.tx.bridgeCrabMessages.setOperatingMode`

+ + + - **summary**: Halt or resume all/some pallet operations.

+ + + setOwner(newOwner:AccountId32) + + + - **interface**: `api.tx.bridgeCrabMessages.setOwner`

+ + + - **summary**: Change `PalletOwner`, May only be called either by root, or by `PalletOwner`.

+ + + + + updatePalletParameter(parameter:DarwiniaRuntimeBridgesMessageCrabDarwiniaToCrabMessagesParameter) + + + - **interface**: `api.tx.bridgeCrabMessages.updatePalletParameter`

+ + + - **summary**: Update pallet parameter, May only be called either by root, or by `PalletOwner`.

+ + + + + + +feeMarket +

+ + + enrollAndLockCollateral(lockCollateral:u128, relayFee:u128) + + + - **interface**: `api.tx.feeMarket.enrollAndLockCollateral`

+ + + - **summary**:Any accounts can enroll to be a relayer by lock collateral. The relay fee is optional.

+ + cancelEnrollment() + + + - **interface**: `api.tx.feeMarket.cancelEnrollment`

+ + + - **summary**: Cancel enrolled relayer.

+ + + setAssignedRelayersNumber(number:u32) + + + - **interface**: `api.tx.feeMarket.setAssignedRelayersNumber`

+ + + - **summary**: Set the account of assigned relayers(Only for sudo).

+ + + + setSlashProtect(slashProtect:u128) + + + - **interface**: `api.tx.feeMarket.setSlashProtect`

+ + + - **summary** Set the maximum allowed slash value for the assigned relayer(Only for sudo).

+ + + updateLockedCollateral(newCollateral:u128) + + + - **interface**: `api.tx.feeMarket.updateLockedCollateral`

+ + + - **summary**:Update locked collateral for enrolled relayer, only supporting lock more.

+ + + updateRelayFee(newFee:u128) + + + - **interface**: `api.tx.feeMarket.updateRelayFee`

+ + + - **summary**:Update relay fee for enrolled relayer.

+ + +ktonTreasury +

+ + + + + approveProposal(proposalId:u32) + + + - **interface**: `api.tx.ktonTreasury.approveProposal`

+ + + - **summary**:Approve a proposal. At a later time, the proposal will be allocated to the beneficiary and the original deposit will be returned.

+ + + + proposeSpend(value:u128, beneficiary:MultiAddress) + + + - **interface**: `api.tx.ktonTreasury.proposeSpend`

+ + + - **summary**:Put forward a suggestion for spending. A deposit proportional to the value is reserved and slashed if the proposal is rejected. It is returned once the proposal is awarded.

+ + +rejectProposal(proposalId:u32) + + + - **interface**: `api.tx.ktonTreasury.rejectProposal`

+ + + - **summary**:Reject a proposed spend. The original deposit will be slashed.

+ + +phragmenElection +

+ + + + cleanDefunctVoters(numVoters:u32, numDefunct:u32) + + + - **interface**: `api.tx.phragmenElection.cleanDefunctVoters`

+ + + - **summary**:Clean all voters who are defunct. deposit of the removed voters are returned.

+ + + + + removeMember(who:MultiAddress, hasReplacement:boolean) + + + - **interface**: `api.tx.phragmenElection.removeMember`

+ + + - **summary**:Remove a particular member from the set. This is effective immediately and the bond of the outgoing member is slashed.

+ + + +removeVoter() + + + - **interface**: `api.tx.phragmenElection.removeVoter`

+ + + - **summary**:Remove `origin` as a voter.

+ + +renounceCandidacy(renouncing:PalletElectionsPhragmenRenouncing) + + + - **interface**: `api.tx.phragmenElection.renounceCandidacy`

+ + + - **summary**:Renounce one's intention to be a candidate for the next election round.

+ +submitCandidacy(candidateCount:u32) +

+ + - **interface**: `api.tx.phragmenElection.submitCandidacy`

+ + + - **summary**:Submit oneself for candidacy. A fixed amount of deposit is recorded.

+ + + +vote(votes:AccountId32,value:u128) + + - **interface**: `api.tx.phragmenElection.vote`

+ + + - **summary**:Vote for a set of candidates for the upcoming round of election. This can be called to set the initial votes, or update already existing votes.

+ + + +kton +

+ + +forceTransfer(source:MultiAddress,dest:MultiAddress, value:u128 ) + + + - **interface**: `api.tx.kton.forceTransfer`

+ + + - **summary**:Exactly as `transfer`, except the origin must be root and the source account may be specified.

+ + + + + forceUnreserve(who:MultiAddress, amount:u128 ) + + + - **interface**: `api.tx.kton.forceUnreserve`

+ + + - **summary**:Unreserve some balance from a user by force.

+ + +setBalance(who:MultiAddress, newFree:u128, newReserved:u128 ) + + + - **interface**: `api.tx.kton.setBalance`

+ + + - **summary**:Set the balances of a given account.

+ + + +transfer(dest:MultiAddress, value:u128 ) + + + - **interface**: `api.tx.kton.transfer`

+ + + - **summary**:Transfer some liquid free balance to another account.

+ + + + +transferAll(dest:MultiAddress, keepAlive:boolean ) + + + - **interface**: `api.tx.kton.transferAll`

+ + + - **summary**:Transfer the entire transferable balance from the caller account.

+ + + + transferKeepAlive(dest:MultiAddress, value:u128 ) + + + - **interface**: `api.tx.kton.transferKeepAlive`

+ + + - **summary**:Same as the [`transfer`] call, but with a check that the transfer will not kill the origin account.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/sdk/darwinia.js/Substrate API/Storage.md b/docs/sdk/darwinia.js/Substrate API/Storage.md new file mode 100644 index 00000000..9fa9ce86 --- /dev/null +++ b/docs/sdk/darwinia.js/Substrate API/Storage.md @@ -0,0 +1,468 @@ +--- +sidebar_position: 6 +--- + +# Storage + + + +The following sections contain Storage methods are part of the default Darwinia runtime. On the api, these are exposed via api.query.``.``. + +(NOTE: These were generated from a static/snapshot view of a recent Darwinia master node. Some items may not be available in older nodes, or in any customized implementations.) + + + +- [bridgeCrabGrandpa](#bridgeCrabGrandpa) +- [bridgeCrabMessages](#bridgeCrabMessages) +- [darwiniaHeaderMMR](#darwiniaHeaderMMR) +- [feeMarket](#feeMarket) +- [ktonTreasury](#ktonTreasury) +- [phragmenElection](#phragmenElection) +- [kton](#kton) + + + +*** + + +bridgeCrabGrandpa +

+ + + bestFinalized():H256 + + + - **interface**: `api.query.bridgeCrabGrandpa.bestFinalized`

+ + + - **summary**: Hash of the best finalized header.

+ + + currentAuthoritySet():BpHeaderChainAuthoritySet + + + + - **interface**: `api.query.bridgeCrabGrandpa.currentAuthoritySet`

+ + + - **summary**: The current GRANDPA Authority set.

+ + + + + + + importedHashes(arg:u32):Option <H256> + + + - **interface**: `api.query.bridgeCrabGrandpa.importedHashes`

+ + + - **summary**: A ring buffer of imported hashes. Ordered by the insertion time.

+ + + + +importedHashesPointer():u32 + + + - **interface**: `api.query.bridgeCrabGrandpa.importedHashesPointer`

+ + + - **summary**: Current ring buffer position.

+ + +importedHeaders(arg:H256):Option<SpRuntimeHeader> + + + - **interface**: `api.query.bridgeCrabGrandpa.importedHeaders`

+ + + - **summary**: Headers which have been imported into the pallet.

+ + + +initialHash():H256 + + + - **interface**: `api.query.bridgeCrabGrandpa.initialHash`

+ + + - **summary**: Hash of the header used to bootstrap the pallet.

+ + + +isHalted():bool + + + - **interface**: `api.query.bridgeCrabGrandpa.isHalted`

+ + + - **summary**: If true, all pallet transactions are failed immediately.

+ + +palletOwner():Option<AccountId32> + + + - **interface**: `api.query.bridgeCrabGrandpa.palletOwner`

+ + + - **summary**: Optional pallet owner.

+ + +requestCount():u32 + + + - **interface**: `api.query.bridgeCrabGrandpa.requestCount`

+ + + - **summary**: The current number of requests which have written to storage.

+ + + + + + + +bridgeCrabMessages +

+ + + +inboundLanes(arg:U8aFixed):BpMessagesInboundLaneData + + + - **interface**: `api.query.bridgeCrabMessages.inboundLanes`

+ + + - **summary**:Map of lane id => inbound lane data.

+ + +outboundLanes(arg:U8aFixed):BpMessagesInboundLaneData + + + - **interface**: `api.query.bridgeCrabMessages.outboundLanes`

+ + + - **summary**:Map of lane id => outbound lane data.

+ +outboundMessages(arg:BpMessagesMessageKey):Option<BpMessagesMessageData> + + + - **interface**: `api.query.bridgeCrabMessages.outboundMessages`

+ + + - **summary**:All queued outbound messages.

+ + + + +palletOperatingMode():BpMessagesOperatingMode + + + - **interface**: `api.query.bridgeCrabMessages.palletOperatingMode`

+ + + - **summary**:The current operating mode of the pallet.

+ + +palletOwner():Option&lr;AccountId32> + + - **interface**: `api.query.bridgeCrabMessages.palletOwner`

+ + + - **summary**:Optional pallet owner.

+ + + + + +darwiniaHeaderMMR +

+ + + +migrationStep():u32 + + + - **interface**: `api.query.darwiniaHeaderMMR.migrationStep`

+ + + - **summary**:Migration step.

+ + + +mmrSize():u64 + + + - **interface**: `api.query.darwiniaHeaderMMR.mmrSize`

+ + + - **summary**:Size of the MMR.

+ + + + +peaks(arg:u64):Option<H256> + + + - **interface**: `api.query.darwiniaHeaderMMR.peaks`

+ + + - **summary**:Peaks of the MMR.

+ + + + +feeMarket +

+ + + + +assignedRelayers():Option<Vec<PalletFeeMarketRelayer>> + + + - **interface**: `api.query.feeMarket.assignedRelayers`

+ + + - **summary**: The assigned relayers at this moment, empty if the registered assigned relayers not enough.

+ + + assignedRelayersNumber():u32 + + + - **interface**: `api.query.feeMarket.assignedRelayersNumber`

+ + + - **summary**: The assigned relayers number.

+ + + + collateralSlashProtect():Option<u128> + + + - **interface**: `api.query.feeMarket.collateralSlashProtect`

+ + + - **summary**: The maximum slash value for assigned relayer.

+ + + + orders(arg:ITuple<[U8aFixed, u64]>):Option<PalletFeeMarketOrder> + + + - **interface**: `api.query.feeMarket.orders`

+ + + - **summary**: Order storage, please note that the order storage will be deleted after confirmed.

+ + + + relayers():Vec<AccountId32> + + + - **interface**: `api.query.feeMarket.relayers`

+ + + - **summary**: List of all relayers.

+ + + + relayersMap(arg:AccountId32):PalletFeeMarketRelayer + + + - **interface**: `api.query.feeMarket.relayersMap`

+ + + - **summary**: The relayer's detail info.

+ + + + +ktonTreasury +

+ + + + + approvals():Vec<u32> + + + - **interface**: `api.query.ktonTreasury.approvals`

+ + + - **summary**:Proposal indices that have been approved but not yet awarded.

+ + + + proposalCount():u32 + + + - **interface**: `api.query.ktonTreasury.proposalCount`

+ + + - **summary**:Number of proposals that have been made.

+ + + +proposals(arg:u32):Option<PalletTreasuryProposal> + + + - **interface**: `api.query.ktonTreasury.proposals`

+ + + - **summary**:Proposals that have been made.

+ + + +phragmenElection +

+ + + +candidates(arg:u32):Vec<ITuple<[AccountId32, u128]>> + + + - **interface**: `api.query.phragmenElection.candidates`

+ + + - **summary**:The present candidate list. A current member or runner-up can never enter this vector and is always implicitly assumed to be a candidate.

+ + + +electionRounds():u32 + + + - **interface**: `api.query.phragmenElection.electionRounds`

+ + + - **summary**:The total number of vote rounds that have happened, excluding the upcoming one.

+ + + + members():Vec<PalletElectionsPhragmenSeatHolder> + + + - **interface**: `api.query.phragmenElection.members`

+ + + - **summary**:The current elected members.

+ + + + runnersUp():Vec<PalletElectionsPhragmenSeatHolder> + + + - **interface**: `api.query.phragmenElection.runnersUp`

+ + + - **summary**:The current reserved runners-up.

+ + + voting(arg:AccountId32):PalletElectionsPhragmenVoter + + + - **interface**: `api.query.phragmenElection.voting`

+ + + - **summary**:Votes and locked stake of a particular voter.

+ + + +kton +

+ + + + account(arg:AccountId32):DarwiniaCommonRuntimeImplsAccountData + + + - **interface**: `api.query.kton.account`

+ + + - **summary**:The balance of an account.

+ + + + + locks(arg:AccountId32):Vec<PalletBalancesBalanceLock> + + + - **interface**: `api.query.kton.locks`

+ + + - **summary**:Any liquidity locks on some account balances.

+ + +reserves(arg:AccountId32):Vec<DarwiniaBalancesReserveData> + + + - **interface**: `api.query.kton.reserves`

+ + + - **summary**:Named reserves on some account balances.

+ + + + storageVersion():DarwiniaBalancesReleases + + + - **interface**: `api.query.kton.storageVersion`

+ + + - **summary**:Storage version of the pallet.

+ + + + + totalIssuance():u128 + + + - **interface**: `api.query.kton.totalIssuance`

+ + + - **summary**:The total units issued in the system.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/sdk/darwinia.js/Substrate API/api-derive.md b/docs/sdk/darwinia.js/Substrate API/api-derive.md new file mode 100644 index 00000000..11d5d9b2 --- /dev/null +++ b/docs/sdk/darwinia.js/Substrate API/api-derive.md @@ -0,0 +1,100 @@ +--- +sidebar_position: 2 +--- + +# API-Derive + + + + +Common function derived from RPC calls and storage queries. Note that darwinia.js libary version must be greater than v2.8.0 to include the api-derive feature. + +Install it in your project directory with the following command: + +```json + yarn add @darwinia/api-derive +``` + +Inject our **darwiniaDerive** when creating API instance + +```typescript +// Import +import { ApiPromise, WsProvider } from '@polkadot/api'; +import { darwiniaDerive } from '@darwinia/api-derive/bundle'; +import { typesBundle } from "@darwinia/types/mix"; +... + +// Construct +const wsProvider = new WsProvider('wss://rpc.darwinia.network'); +const api = await ApiPromise.create({ provider: wsProvider, typesBundle: typesBundle.spec.darwinia, derives: darwiniaDerive }); + +``` + +Since you are already familiar with the api.query interface, the api.derive interface follows the same format, for instance **usableBalance** derived function to query account's RING Balance. + +```typescript +// Import darwinia token type (ring, kton) +import { TokenType } from '@darwinia/api-derive/accounts/types'; +// Initialize the API as in previous sections injecting darwiniaDerive +... + +// The actual address that we will use +const ADDR = '
'; +await api.derive.usableBalance.balance(TokenType.Ring, ADDR).then((balance) => { + console.log(` ring usable balance ${balance.usableBalance} `) + +``` + +#### Customer Api-Derive + +Darwinia.js allow application developer to extend their derived method. first you should put function declaration in ExactDerive interface. for example there is 'custome.something' augmentation. + +```typescript +// augmentDerives.ts +import type { Observable } from "rxjs"; + +declare module "@polkadot/api-derive/derive" { + // extend, add our custom section + export interface ExactDerive { + custom: { + something: ReturnType<() => () => Observable>; + }; + } +} +``` + +and then, ensure 'custom.somethinig' augmentation is applied. + +```typescript +// customeDerive.ts +custom: { + something: () => (): Observable => from([1, 2, 3]); +} +``` + +create api instance to use this derived api. + +```typescript +import { custom } from "customeDerive.ts"; +import { darwiniaDerive } from "@darwinia/api-derive/bundle"; +import { DeriveCustom } from "@polkadot/api/types"; + +const cutomeDerives = { + ...darwiniaDerive, // it's optinal + // assignment your augmentation + custom: { + something: custome.something, + }, +} as DeriveCustom; + +const api = await ApiPromise.create({ + provider: wsProvider, + typesBundle: typesBundle.spec.darwinia, + derives: cutomeDerives, +}); + +// your derived method +await api.derive.custom.something().then((res) => { + console.log(`somthing is ${res}`); // return [1,2,3] +}); +``` \ No newline at end of file diff --git a/docs/sdk/darwinia.js/Substrate API/overview.md b/docs/sdk/darwinia.js/Substrate API/overview.md new file mode 100644 index 00000000..4d9404bd --- /dev/null +++ b/docs/sdk/darwinia.js/Substrate API/overview.md @@ -0,0 +1,115 @@ +--- +sidebar_position: 1 +--- + +# Overview + + +[Darwinia.js](https://github.com/darwinia-network/darwinia.js) API library allows application developers to query Darwinia and Pangoro chain and interact with the chain's substrate interfaces using JavaScript. In this docs, we will look into how we can use some commonly code example to interact with Darwinia node using Darwinia.js API library. + +### Dependencies + +The library sample mainly depends on the following libraries: + +- @polkadot/api The polkadot api library provides a Promise-style interface for performing related operations on the Darwinia chain + +- ethers.js The ethers aims to be a complete and compact library for interacting with the Ethereum Blockchain and its ecosystem. + +### Usage + +Install library + +```nodejs + +yarn add @darwinia/api-options + +``` + +Darwinia.js include Darwinia, Pangoro chain interfaces for developer to interact one of them. In this you want to query and interact Darwinia node. Here is a config sample for using those node interfaces. we must configure **tsconfig.json** at compilerOptions section to apply type augmentation explicitly. + + + +1. Applying Darwinia Chain type augmentation in tsconfig.json + +```json +{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "@polkadot/api-augment": ["./node_modules/@darwinia/api-augment/index.d.ts"], + "@polkadot/types-augment": ["./node_modules/@darwinia/types/interfaces/augment-types.d.ts"], + "@polkadot/rpc-augment": ["./node_modules/@darwinia/rpc-augment/index.d.ts"], + "@polkadot/types/lookup": ["./node_modules/@darwinia/types-augment/index.d.ts"] + } + } +} +``` + + +2. Applying Pangoro Chain type augmentation in tsconfig.json + + + +``` json +{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "@polkadot/api-augment": ["./node_modules/@darwinia/api-augment/pangoro/index.d.ts"], + "@polkadot/types-augment": ["./node_modules/@darwinia/types/interfaces/augment-types.d.ts"], + "@polkadot/rpc-augment": ["./node_modules/@darwinia/rpc-augment/pangoro/index.d.ts"], + "@polkadot/types/lookup": ["./node_modules/@darwinia/types-augment/lookup/pangoro/index.d.ts"] + } + } +} + +``` + + +#### Create API Instance + +You must first instantiate an API instance of the darwinia.js api. Create the wsProvider using the websocket endpoint of the Darwinia node. + +```typescript +// Import +import { ApiPromise, WsProvider } from '@polkadot/api'; +... +// Construct with darwinia node endpoint +const wsProvider = new WsProvider('wss://rpc.darwinia.network'); +const api = await ApiPromise.create({ provider: wsProvider }); + +// Do something +console.log(api.genesisHash.toHex()); + +``` + +Due to darwinia has own substrate module and types, this mean developers are adding sepcific types for implementation as well. to close the gap, we have define types for different node spec versions. you could inject types by our **typesBundle** . let's change instantiate api instance to let Api know our types. + +```typescript +// Import +import { ApiPromise, WsProvider } from '@polkadot/api'; +import { typesBundle } from "@darwinia/types/mix"; +... +// Construct +const wsProvider = new WsProvider('wss://rpc.darwinia.network'); +const api = await ApiPromise.create({ provider: wsProvider, typesBundle: typesBundle.spec.darwinia }); + +// Do something +console.log(api.genesisHash.toHex()); + +``` + + + + +#### Metadata and API Decoration + +It's useful to understand some basic workings of the library. +When the API connects to a node, one of the first things it does is to retrieve the metadata and decorate the API based on the metadata information. The metadata effectively provides data in the form of api.``.``.`
` that fits into one of the following `` categories: consts, query and tx. + +None of the information contained within the api.{consts, query, tx}.``.`` endpoints are hard coded in the API. Rather everything is fully decorated by what the metadata exposes and is therefore completely dynamic. This means that when you connect to different chains, the metadata and API decoration will change and the API interfaces will reflect what is available on the chain you are connected to. + +#### API Example + +We take some common examples on ApiPromise version of API, They are same with Polkadot.js API allow application developers to interact with node's interface +including "runtime constants", "state queries", "RPC queries" and so on. You can check the [Polkadot Docs](https://polkadot.js.org/docs/api/start) for more detail usage description. \ No newline at end of file diff --git a/docs/sdk/darwinia.js/Substrate API/rpc.md b/docs/sdk/darwinia.js/Substrate API/rpc.md new file mode 100644 index 00000000..69f48be9 --- /dev/null +++ b/docs/sdk/darwinia.js/Substrate API/rpc.md @@ -0,0 +1,72 @@ +--- +sidebar_position: 5 +--- + +# RPC + + + +The following sections contain known RPC methods that may be available on Darwinia nodes and allow you to interact with the Darwinia node, query, and submit. + + +- [net](#net) +- [web3](#web3) + +*** + + +net +

+ + + listening():bool + + + - **interface**: `api.rpc.net.listening`

+ + + - **summary**:Returns true if client is actively listening for network connections. Otherwise false.

+ + + peerCount():Text + + + - **interface**: `api.rpc.net.peerCount`

+ + + - **summary**:Returns number of peers connected to node.

+ + + + version():Text + + + - **interface**: `api.rpc.net.version`

+ + + - **summary**:Returns protocol version.

+ + + +web3 +

+ + + + clientVersion():Text + + + - **interface**: `api.rpc.web3.clientVersion`

+ + + - **summary**:Returns current client version.

+ + + sha3(data:Bytes):H256 + + + - **interface**: `api.rpc.web3.sha3`

+ + + - **summary**:Returns sha3 of the given data.

+ diff --git a/docs/sdk/darwinia.js/substrate-api.md b/docs/sdk/darwinia.js/substrate-api.md deleted file mode 100644 index b94e0300..00000000 --- a/docs/sdk/darwinia.js/substrate-api.md +++ /dev/null @@ -1,380 +0,0 @@ ---- -sidebar_position: 3 ---- - -# Substrate API - -### Introduction - -[Darwinia.js](https://github.com/darwinia-network/darwinia.js) API library allows application developers to query Darwinia, Pangoro chain and interact with the chain's substrate interfaces using JavaScript. In this docs, we will look into how we can use some commonly code example to interact with Darwinia node using Darwinia.js API library. - -### Dependencies - -The library sample mainly depends on the following libraries: - -- @polkadot/api The polkadot api library provides a Promise-style interface for performing related operations on the Darwinia chain - -- ethers.js The ethers aims to be a complete and compact library for interacting with the Ethereum Blockchain and its ecosystem. - -### Usage - -Install libarries - -```nodejs - -yarn add @polkadot/api \ - @darwinia/types \ - @darwinia/api-augment \ - @darwinia/types-augment \ - @darwinia/rpc-augment \ - @darwinia/types-known - -``` - -Darwinia.js include Darwinia, Pangoro chain interfaces for developer to interact one of them. In this you want to query and interact Darwinia node. Here is a config sample for using those node interfaces. we must configure **tsconfig.json** at compilerOptions section to apply type augmentation explicitly. - - - -1. applying Darwinia Chain type augmentation in tsconfig.json - -```json -{ - "compilerOptions": { - "baseUrl": ".", - "paths": { - "@polkadot/api-augment": ["./node_modules/@darwinia/api-augment/index.d.ts"], - "@polkadot/types-augment": ["./node_modules/@darwinia/types/interfaces/augment-types.d.ts"], - "@polkadot/rpc-augment": ["./node_modules/@darwinia/rpc-augment/index.d.ts"], - "@poladot/types/lookup": ["./node_modules/@darwinia/types-augment/index.d.ts"] - } - } -} -``` - - -2. applying Pangoro Chain type augmentation in tsconfig.json - - - -``` json -{ - "compilerOptions": { - "baseUrl": ".", - "paths": { - "@polkadot/api-augment": ["./node_modules/@darwinia/api-augment/pangoro/index.d.ts"], - "@polkadot/types-augment": ["./node_modules/@darwinia/types/interfaces/augment-types.d.ts"], - "@polkadot/rpc-augment": ["./node_modules/@darwinia/rpc-augment/pangoro/index.d.ts"], - "@poladot/types/lookup": ["./node_modules/@darwinia/types-augment/lookup/pangoro/index.d.ts"] - } - } -} - -``` - - -#### Create API Instance - -You must first instantiate an API instance of Darwinia.js api. Create the wsProvider using the websocket endpoint of the Darwinia node. - -```typescript -// Import -import { ApiPromise, WsProvider } from '@polkadot/api'; -... -// Construct with darwinia node endpoint -const wsProvider = new WsProvider('wss://rpc.darwinia.network'); -const api = await ApiPromise.create({ provider: wsProvider }); - -// Do something -console.log(api.genesisHash.toHex()); - -``` - -Due to darwinia has own substrate module and types, this mean developers are adding sepcific types for implementation as well. to close the gap, we have define types for different node spec versions. you could inject types by our **typesBundle** . let's change instantiate api instance to let Api know our types. - -```typescript -// Import -import { ApiPromise, WsProvider } from '@polkadot/api'; -import { typesBundle } from "@darwinia/types/mix"; -... -// Construct -const wsProvider = new WsProvider('wss://rpc.darwinia.network'); -const api = await ApiPromise.create({ provider: wsProvider, typesBundle: typesBundle.spec.darwinia }); - -// Do something -console.log(api.genesisHash.toHex()); - -``` - - -#### Metadata and API Decoration - -It's useful to understand some basic workings of the library. -When the API connects to a node, one of the first things it does is to retrieve the metadata and decorate the API based on the metadata information. The metadata effectively provides data in the form of api.``.``.`
` that fits into one of the following `` categories: consts, query and tx. - -None of the information contained within the api.{consts, query, tx}.``.`` endpoints are hard coded in the API. Rather everything is fully decorated by what the metadata exposes and is therefore completely dynamic. This means that when you connect to different chains, the metadata and API decoration will change and the API interfaces will reflect what is available on the chain you are connected to. - -### Storage Queries - -This section will walk through the concepts behind making queries to the chain to retrieve current state. The api.query.``.`` interfaces,The API uses the metadata information provided to construct queries based on the location and parameters provided to generate state keys, and then queries these via RPC. - -Here is a code sample for retrieving basic account information given its address: - -```typescript -// Initialize the API as in previous sections using darwinia node -... -// The actual address that we will use -const ADDR = '
'; -// Retrieve the last timestamp -const now = await api.query.timestamp.now(); - -// Retrieve the account balance & nonce via the system module -const { nonce, data: balance } = await api.query.system.account(ADDR); - -console.log(`${now}: balance of Ring ${balance.free}, balance of Kton ${balance.freeKton} and a nonce of ${nonce}`); - -``` - -#### Query Subscription - -In this example we will expand on that knowledge to introduce subscriptions to stream results from the state, as it changes between blocks. - -Here is an example to subscribe to balance changes in an account: - -```typescript -// Initialize the API provider as in the previous section -... -// Define wallet address -const addr = '
'; - -// Subscribe to balance changes for a specified account -const unsub = await api.query.system.account(addr, ({ nonce, data: balance }) => { - console.log(`${now}: balance of Ring ${balance.free}, balance of Kton ${balance.freeKton} and a nonce of ${nonce}`); -}); - -``` - -it returns a subscription unsub() function that can be used to stop the subscription and clear up any underlying RPC connections. The supplied callback will contain the value as it changes, streamed from the node. - -#### Multi Queryies - -It is useful to monitor a number of like-queries at the same time. For instance, we may want to track the balances for a list of accounts we have. The api.query interfaces allows this via the .multi subscription call. - -```typescript -// Subscribe to balance changes for 2 accounts, ADDR1 & ADDR2 (already defined) -const unsub = await api.query.system.account.multi( - [ADDR1, ADDR2], - (balances) => { - const [{ data: balance1 }, { data: balance2 }] = balances; - - console.log( - `The balances are ${balance1.free} and ${balance2.free}` - ); - } -); -``` - -For queries of the same type we can use .multi, for example to retrieve the balances of a number of accounts at once - -### RPC Queries - -The RPC calls provide the backbone for the transmission of data to and from the node. This means that all API endpoints such as api.query, api.tx or api.derive just wrap RPC calls, providing information in the encoded format as expected by the node. - -The api.rpc interface follows the same format api.query. - -```typescript -// Initialize the API provider as in the previous section -... - -// Retrieve the chain & node information information via rpc calls -const [chain, nodeName, nodeVersion, metadata] = await Promise.all([ - api.rpc.system.chain(), - api.rpc.system.name(), - api.rpc.system.version(), - api.rpc.state.getMetadata() - ]); - -console.log(`You are connected to chain ${chain} using ${nodeName} v${nodeVersion} metadata ${metadata}`); - -``` - -### System Events - -You can subscribe system event and extract information from them. - -```typescript - -// Initialize the API provider as in the previous section -... - -// Subscribe to system events via storage -api.query.system.events((events) => { - console.log(`\nReceived ${events.length} events:`); - - // Loop through the Vec - events.forEach((record) => { - // Extract the phase, event and the event types - const { event, phase } = record; - const types = event.typeDef; - - // Show what we are busy with - console.log(`\t${event.section}:${event.method}:: (phase=${phase.toString()})`); - console.log(`\t\t${event.meta.documentation.toString()}`); - - // Loop through each of the parameters, displaying the type and data - event.data.forEach((data, index) => { - console.log(`\t\t\t${types[index].type}: ${data.toString()}`); - }); - }); - -``` - -### Keyring - -Key management of user accounts including generation and retrieval of keyring pairs from a variety of input combinations and the signing of any data. - -you can create an instance by just creating an instance of the **Keyring** class - -```typescript -// Import the keyring as required -import { Keyring } from '@polkadot/api'; -// Initialize the API as we would normally do -... -// Create a keyring instance -const keyring = new Keyring({ type: 'sr25519' }); - -``` - -### Transactions - -Transaction endpoints are exposed, as determined by the metadata, on the api.tx endpoint. These allow you to submit transactions for inclusion in blocks, be it transfers, setting information or anything else your chain supports. - -This is an example of sending a basic transaction - -```javascript -// Initialize the API provider as in the previous section -... - -const BOB = ''; -const transferAmount = '123456789'; -// Create a extrinsic, transferring amount units to Bob. -const transfer = api.tx.balances.transfer(BOB, transferAmount); -const keyring = new Keyring({ type: 'sr25519' }); - -// Add Alice to our keyring with a private key -const alice = keyring.addFromUri('*** mnemonic ***'); - -await transfer.signAndSend(alice, ({ events = [], status }) => { - if (status.isInBlock) { - console.log('Successful transfer of ' + transferAmount + ' with hash ' + status.asInBlock.toHex()); - } else { - console.log('Status of transfer: ' + status.type); - } - - events.forEach(({ phase, event: { data, method, section } }) => { - console.log(phase.toString() + ' : ' + section + '.' + method + ' ' + data.toString()); - if (status.type === 'Finalized' && section + '.' + method === 'system.ExtrinsicSuccess') { - console.log('transfer success'); - api.disconnect(); - } - }); - -``` - -Any transaction will emit events, as a bare minimum this will always be either a system.ExtrinsicSuccess or system.ExtrinsicFailed event for the specific transaction. These provide the overall execution result for the transaction, i.e. execution has succeeded or failed. - -### API-Derive - -Common function derived from RPC calls and storage queries. Note that Darwinia.js libary version must be greate than v2.8.0 including api-derive feature. - -Install it in your project directory with the following command: - -```json - yarn add @darwinia/api-derive -``` - -Inject our **darwiniaDerive** when creating API instance - -```typescript -// Import -import { ApiPromise, WsProvider } from '@polkadot/api'; -import { darwiniaDerive } from '@darwinia/api-derive/bundle'; -import { typesBundle } from "@darwinia/types/mix"; -... - -// Construct -const wsProvider = new WsProvider('wss://rpc.darwinia.network'); -const api = await ApiPromise.create({ provider: wsProvider, typesBundle: typesBundle.spec.darwinia, derives: darwiniaDerive }); - -``` - -Since you are already familiar with the api.query interface, the api.derive interface follows the same format, for instance **usableBalance** derived function to query account's Ring Balance. - -```typescript -// Import darwinia token type (ring, kton) -import { TokenType } from '@darwinia/api-derive/accounts/types'; -// Initialize the API as in previous sections injecting darwiniaDerive -... - -// The actual address that we will use -const ADDR = '
'; -await api.derive.usableBalance.balance(TokenType.Ring, ADDR).then((balance) => { - console.log(` ring usable balance ${balance.usableBalance} `) - -``` - -#### Customer Api-Derive - -Darwinia.js allow application developer to extend their derived method. first you should put function declaration in ExactDerive interface. for example there is 'custome.something' augmentation. - -```typescript -// augmentDerives.ts -import type { Observable } from "rxjs"; - -declare module "@polkadot/api-derive/derive" { - // extend, add our custom section - export interface ExactDerive { - custom: { - something: ReturnType<() => () => Observable>; - }; - } -} -``` - -and then, ensure 'custom.somethinig' augmentation is applied. - -```typescript -// customeDerive.ts -custom: { - something: () => (): Observable => from([1, 2, 3]); -} -``` - -create api instance to use this derived api. - -```typescript -import { custom } from "customeDerive.ts"; -import { darwiniaDerive } from "@darwinia/api-derive/bundle"; -import { DeriveCustom } from "@polkadot/api/types"; - -const cutomeDerives = { - ...darwiniaDerive, // it's optinal - // assignment your augmentation - custom: { - something: custome.something, - }, -} as DeriveCustom; - -const api = await ApiPromise.create({ - provider: wsProvider, - typesBundle: typesBundle.spec.darwinia, - derives: cutomeDerives, -}); - -// your derived method -await api.derive.custom.something().then((res) => { - console.log(`somthing is ${res}`); // return [1,2,3] -}); -``` - - -