@polkadot/types#Null TypeScript Examples

The following examples show how to use @polkadot/types#Null. 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: utils.ts    From subsocial-js with GNU General Public License v3.0 6 votes vote down vote up
constructor (value?: T) {
    const textOrNull = value || new Null(registry)
    super(registry, 'u64', textOrNull)
  }
Example #2
Source File: utils.ts    From subsocial-js with GNU General Public License v3.0 6 votes vote down vote up
constructor (value?: T) {
    const boolOrNull = typeof value === 'boolean' ? value : new Null(registry)
    super(registry, 'bool', boolOrNull)
  }
Example #3
Source File: utils.ts    From subsocial-js with GNU General Public License v3.0 6 votes vote down vote up
constructor (value?: OptionTextType) {
    const textOrNull = nonEmptyStr(value) ? value : new Null(registry)
    super(registry, 'Text', textOrNull)
  }
Example #4
Source File: council.ts    From community-repo with GNU General Public License v3.0 4 votes vote down vote up
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 })
  // made this example with historical data, so you can check different councils/stages
  const blocks :number[] = [259200, 259201]

  // discounting this voter
  const joystreamVoter = "5CJzTaCp5fuqG7NdJQ6oUCwdmFHKichew8w4RZ3zFHM8qSe6"

  const councils: CouncilData[] = []
  for (let i=0; i<blocks.length; i++) {
    const councilMembers: CouncilMemberData[] = []
    const blockHash = await api.rpc.chain.getBlockHash(blocks[i]) as Hash
    const electionStatus = await api.query.councilElection.stage.at(blockHash) as Option<ElectionStage>
    const electionRound = await api.query.councilElection.round.at(blockHash) as u32
    console.log(`
      at block: ${blocks[i]},
      the election stage was: ${electionStatus.value.toString()},
      of election round: ${electionRound.toNumber()},
    `)
    if (electionStatus.value instanceof ElectionStage) {
      const electionStage = electionStatus.unwrap()
      if (electionStage.value instanceof Announcing) {
        console.log("In 'Announcing' stage - ends at block", electionStage.value.toNumber())
      } else if (electionStage.value instanceof Voting) {
        console.log("In 'Voting' stage - ends at block", electionStage.value.toNumber())
      } else if (electionStage.value instanceof Revealing) {
        console.log("In 'Revealing' stage - ends at block", electionStage.value.toNumber())
      } else {
      }
    }
    const activeCouncil = await api.query.council.activeCouncil.at(blockHash) as Seats
    if (!activeCouncil.isEmpty) {
      const elected: Participant[] = []
      for (let member of activeCouncil) {
        let otherStake = 0
        let jsgStake = 0
        const councilMemberId = await getParticipantAt(api, member.member, blockHash)
        const voters: VoterData[] = []
        elected.push(councilMemberId)
        for (let backer of member.backers) {
          const voterId = await getParticipantAt(api, backer.member, blockHash)
          const voter: VoterData = {
            voterId,
            voterStake: backer.stake.toNumber(),
            stakeRatioExJSGvotes: 0,
            kpiRewardRatio: 0,
          }
          otherStake += backer.stake.toNumber()
          if (backer.member.toString() === joystreamVoter) {
            jsgStake += backer.stake.toNumber()
          }
          voters.push(voter)
        }
        const ownStake = member.stake.toNumber()
        const totalStakeExJSGvotes = member.stake.toNumber() + otherStake - jsgStake
        const totalStake = member.stake.toNumber() + otherStake
        const councilMember: CouncilMemberData = {
          councilMemberId,
          totalStake,
          totalStakeExJSGvotes,
          ownStake,
          otherStake,
          otherStakeExJSGvotes: otherStake - jsgStake,
          stakeRatioExJSGvotes: ownStake/totalStakeExJSGvotes,
          voters,
        }
        councilMembers.push(councilMember)
      }
      let totalStakes = 0
      let totalStakesExJSGvotes = 0
      let ownStakes = 0
      let otherStakes = 0
      let otherStakesExJSGvotes = 0
      
      for (let councilMember of councilMembers) {
        totalStakes += councilMember.totalStake
        totalStakesExJSGvotes += councilMember.totalStakeExJSGvotes
        ownStakes += councilMember.ownStake
        otherStakes += councilMember.otherStake
        otherStakesExJSGvotes += councilMember.otherStakeExJSGvotes
      }
      for (let councilMember of councilMembers) {
        councilMember.kpiRewardRatio = councilMember.ownStake/totalStakesExJSGvotes
        for (let voter of councilMember.voters) {
          if (voter.voterId.accountId != joystreamVoter) {
            voter.stakeRatioExJSGvotes = voter.voterStake/councilMember.totalStakeExJSGvotes
            voter.kpiRewardRatio = voter.voterStake/totalStakesExJSGvotes
          }
        }
      }
      const termEnd = (await api.query.council.termEndsAt.at(blockHash) as BlockNumber).toNumber()
      const announcing = (await api.query.councilElection.announcingPeriod.at(blockHash) as BlockNumber).toNumber()
      const voting = (await api.query.councilElection.votingPeriod.at(blockHash) as BlockNumber).toNumber()
      const revealing = (await api.query.councilElection.votingPeriod.at(blockHash) as BlockNumber).toNumber()
      const term = (await api.query.councilElection.newTermDuration.at(blockHash) as BlockNumber).toNumber()
 
      // this will not always be correct...
      const electedAtBlock = termEnd-term
      const newCouncilStartsAt = termEnd+announcing+voting+revealing
      const electedHash = await api.rpc.chain.getBlockHash(electedAtBlock) as Hash
      const getRewardInterval = await api.query.council.payoutInterval.at(electedHash) as Option<BlockNumber>

      const councilMint = await api.query.council.councilMint.at(electedHash) as MintId
      const mintAtStart = await api.query.minting.mints.at(electedHash,councilMint) as Mint
      const mintCapacityAtStart = mintAtStart.capacity.toNumber()
      
      let rewardInterval = 3600
      if (!(getRewardInterval.value instanceof Null)) {
        rewardInterval = getRewardInterval.unwrap().toNumber()
      }

      const rewardamountPerPayout = (await api.query.council.amountPerPayout.at(electedHash) as BalanceOf).toNumber()
      const expectedIndividualRewards = rewardamountPerPayout*term/rewardInterval

      const council: CouncilData = {
        electionCycle: electionRound.toNumber(),
        electedAtBlock,
        mintCapacityAtStart,
        rewardamountPerPayout,
        rewardInterval,
        termEnd: termEnd,
        expectedIndividualRewards,
        newCouncilStartsAt,
        totalStakes,
        totalStakesExJSGvotes,
        ownStakes,
        otherStakes,
        otherStakesExJSGvotes,
        elected,
        electionData: councilMembers,
      }
      const bestHeight = (await api.derive.chain.bestNumber()).toNumber()
      if (bestHeight>newCouncilStartsAt) {
        const endHash = await api.rpc.chain.getBlockHash(newCouncilStartsAt) as Hash
        const mintAtEnd = await api.query.minting.mints.at(endHash,councilMint) as Mint
        council.mintCapacityAtEnd = mintAtEnd.capacity.toNumber()
        council.councilSpending = mintAtEnd.total_minted.toNumber() - mintAtStart.total_minted.toNumber()
      }
      councils.push(council)
    }
  }
  console.log("councils",JSON.stringify(councils, null, 4))
  api.disconnect()
}
Example #5
Source File: working-groups.ts    From community-repo with GNU General Public License v3.0 4 votes vote down vote up
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 })

  const storageProviders: StorageProvider[] = []
  const contentCurators: ContentCurator[] = []

  // get all active storage workers
  const storageWorkerKeys = await api.query.storageWorkingGroup.workerById.keys()
  const storageWorkerIds = storageWorkerKeys.map(({ args: [workerId]}) => workerId) as Vec<WorkerId>
  storageWorkerIds.sort((a,b) => a.toNumber()-b.toNumber())
  console.log('all storageWorkerIds:', storageWorkerIds.join(', '));
  for (let key of storageWorkerIds) {
    const worker = await api.query.storageWorkingGroup.workerById(key) as Worker
    //console.log("worker",worker.toHuman())
    const storageProvider: StorageProvider = {
      workerId: key.toNumber(),
      memberId: worker.member_id.toNumber(),
      roleAccount: worker.role_account_id.toString(),
    }
    if (worker.reward_relationship.isSome) {
      const rewardRelationshipId = worker.reward_relationship.unwrap()
      const rewardRelationship = await api.query.recurringRewards.rewardRelationships(rewardRelationshipId) as RewardRelationship
      //console.log("rewardRelationship",rewardRelationship.toHuman())
      let rewardInterval = 0
      let rewardPerWeek = 0
      if (!(rewardRelationship.payout_interval.value instanceof Null)) {
        rewardInterval = rewardRelationship.payout_interval.unwrap().toNumber()
        rewardPerWeek = rewardRelationship.amount_per_payout.toNumber()*100800/rewardInterval
      }
      storageProvider.rewardRelationship = {
        rewardRelationshipId: rewardRelationshipId.toNumber(),
        rewardSize: rewardRelationship.amount_per_payout.toNumber(),
        rewardInterval,
        rewardPerWeek,
        totalEarned: rewardRelationship.total_reward_received.toNumber(),
        totalMissed: rewardRelationship.total_reward_missed.toNumber(),
      }
    }
    if (worker.role_stake_profile.isSome && !(worker.role_stake_profile instanceof Null)) {
      const stake = worker.role_stake_profile.unwrap()
      const workerStake = await api.query.stake.stakes(stake.stake_id) as Stake
      //console.log("workerStake",workerStake.toHuman())
      const stakingStatus = (workerStake.staking_status as StakingStatus).value
      if (stakingStatus instanceof Staked) {
        storageProvider.stakeProfile = {
          stakeId: stake.stake_id.toNumber(),
          roleStake: stakingStatus.staked_amount.toNumber(),
        }
      }
    }
    storageProviders.push(storageProvider)
  }

  // get all active content curators
  for (let i = 0; i < +(await api.query.contentDirectoryWorkingGroup.activeWorkerCount()).toString(); i++) {
    const curator = await api.query.contentDirectoryWorkingGroup.workerById(i) as WorkerOf
    // filter out inactive
    if (curator.is_active) {
      const nextApplicationId = +(await api.query.contentDirectoryWorkingGroup.nextApplicationId()).toString()
      let applicationId = {} as ApplicationOf
      for (let j = 0; j < nextApplicationId - 1; j++) {
        const appId = await api.query.contentDirectoryWorkingGroup.applicationById(j) as ApplicationOf
        if(appId.member_id?.toNumber() == curator.member_id?.toNumber()) {
          applicationId = appId
          break
        }
      }
      
      const contentCurator: ContentCurator = {
        curatorId: i,
        memberId: applicationId?.member_id.toNumber(),
        roleAccount: curator.role_account_id.toString(),
        applicationId: applicationId?.application_id.toNumber(),
      }
      if (curator.reward_relationship.isSome) {
        const rewardRelationshipId = curator.reward_relationship.unwrap()
        const rewardRelationship = await api.query.recurringRewards.rewardRelationships(rewardRelationshipId) as RewardRelationship
        //console.log("rewardRelationship",rewardRelationship.toHuman())
        let rewardInterval = 0
        let rewardPerWeek = 0
        if (!(rewardRelationship.payout_interval.value instanceof Null)) {
          rewardInterval = rewardRelationship.payout_interval.unwrap().toNumber()
          rewardPerWeek = rewardRelationship.amount_per_payout.toNumber()*100800/rewardInterval
        }
        contentCurator.rewardRelationship = {
          rewardRelationshipId: rewardRelationshipId.toNumber(),
          rewardSize: rewardRelationship.amount_per_payout.toNumber(),
          rewardInterval,
          rewardPerWeek,
          totalEarned: rewardRelationship.total_reward_received.toNumber(),
          totalMissed: rewardRelationship.total_reward_missed.toNumber(),
        }
      }
      if (curator.role_stake_profile.isSome && !(curator.role_stake_profile instanceof Null)) {
        const stake = curator.role_stake_profile.unwrap()
        const workerStake = await api.query.stake.stakes(stake.stake_id) as Stake
        //console.log("workerStake",workerStake.toHuman())
        const stakingStatus = (workerStake.staking_status as StakingStatus).value
        if (stakingStatus instanceof Staked) {
          contentCurator.stakeProfile = {
            stakeId: stake.stake_id.toNumber(),
            roleStake: stakingStatus.staked_amount.toNumber(),
          }
        }
      }
      contentCurators.push(contentCurator)
    }
  }
 console.log("storageProviders",JSON.stringify(storageProviders, null, 4))

 console.log("contentCurators",JSON.stringify(contentCurators, null, 4))





  api.disconnect()
}