Просмотр исходного кода

Merge pull request #245 from singulart/api-script-fix

KPI 14.12 API Scripts Maintenance
mochet 3 лет назад
Родитель
Сommit
70f8c9687b

+ 77 - 26
joystream-api/README.md

@@ -3,46 +3,97 @@
 Repo with examples on how to use the @joystream/types package along with @polkadot/api to communicate with a joystream full node.
 
 
-## Examples
+## Building the code
 
 ```
 yarn && yarn build
-yarn run status
 ```
 
-## Example code
+In case you have a compilation error saying:
 
-```javascript
-import { registerJoystreamTypes } from '@joystream/types';
-import { ApiPromise, WsProvider } from '@polkadot/api';
+```
+node_modules/@joystream/types/content-working-group/index.d.ts:3:22 - error TS2614: Module '"../common"' has no exported member 'Credential'. Did you mean to use 'import Credential from "../common"' instead?
+
+3 import { OptionText, Credential, SlashingTerms } from '../common';
+                       ~~~~~~~~~~
+Found 1 error.
+```
+
+Open the file ```node_modules/@joystream/types/content-working-group/index.d.ts``` in a text editor and remove the failing import, so that the line looks as follows: ``` import { OptionText, SlashingTerms } from '../common'; ```
+
+Save the changes and re-run ```yarn && yarn build``` again, the build should work fine. 
+
+
+## Example Scripts
+
+### [general.js](src/examples/general.ts)
+
+Ideal for newcomers. Contains the very basic APIs usage examples: get the last blockchain finalized block, get total coin issuance. 
+Also shows how to iterate the events inside a given block.
+
+```
+node lib/examples/general.js
+```
+
+### [status.js](src/general/status.ts)
+
+Another good starting point for newcomers to understand how APIs are called.
+
+```
+node lib/general/status.js
+```
 
-async function main () {
-  // Initialise the provider to connect to the local node
-  const provider = new WsProvider('ws://127.0.0.1:9944');
+### [get-media-change.js](src/curators/get-media-change.ts)
 
-  // Register types before creating the API
-  registerJoystreamTypes();
+Shows how to work with Substrate events and Extrinsics to get the information about Joystream media uploads. 
 
-  // Create the API and wait until ready
-  const api = await ApiPromise.create({ provider });
+```
+node lib/curators/get-media-change.js
+```
 
-  // Retrieve the chain & node information information via rpc calls
-  const [chain, nodeName, nodeVersion] = await Promise.all([
-    api.rpc.system.chain(),
-    api.rpc.system.name(),
-    api.rpc.system.version()
-  ]);
+### [council.js](src/examples/council.ts)
 
-  console.log(`Chain ${chain} using ${nodeName} v${nodeVersion}`);
-}
+Shows how to use ```councilElection```, ```minting```, ```council``` APIs. 
 
-main();
+```
+node lib/examples/council.js
 ```
 
-### Scripts
+### [get-events-and-extrinsics.js](src/examples/get-events-and-extrinsics.ts)
 
-You can run scripts that are found in the [./scripts/](./scripts) folder:
+Shows the variety of Substrate event Extrinsic types within a given range of blocks. 
 
-```sh
-yarn script example
 ```
+node lib/examples/get-events-and-extrinsics.js
+```
+
+### [working-groups.js](src/examples/working-groups.ts)
+
+Shows how to use a set of APIs related to Joystream working groups: ```storageWorkingGroup```, ```recurringRewards```, ```contentDirectoryWorkingGroup```. 
+
+```
+node lib/examples/working-groups.js
+```
+
+### [proposals.js](src/examples/proposals.ts)
+
+Shows how to use a APIs related to Joystream DAO proposals ```proposalsEngine```, ```staking```, ```members```. 
+
+```
+node lib/examples/proposals.js
+```
+
+### Javascript scripts
+
+There are some untyped Javascript scripts available for working with the data directory. You can run them using yarn: 
+
+```
+//shows the available scripts
+yarn script index
+
+yarn script exportDataDirectory
+yarn script listDataDirectory
+
+```
+
+or execute them in [Pioneer JS Toolbox](https://testnet.joystream.org/#/js) 

+ 13 - 11
joystream-api/package.json

@@ -5,22 +5,24 @@
   "license": "MIT",
   "scripts": {
     "build": "tsc --build tsconfig.json",
-    "status": "node lib/status",
-    "script": "node lib/script",
+    "status": "node lib/general/status",
+    "script": "node lib/general/script",
     "postinstall": "yarn build"
   },
   "dependencies": {
-    "@joystream/types": "^0.14.0",
-    "@polkadot/api": "1.26.1",
-    "@polkadot/keyring": "^3.0.1",
-    "@polkadot/types": "1.26.1",
-    "@polkadot/util": "^3.0.1",
-    "@polkadot/util-crypto": "^3.0.1",
-    "@types/bn.js": "^4.11.5",
-    "bn.js": "^4.11.8"
+    "@joystream/types": "^0.16.1",
+    "@polkadot/api": "4.2.1",
+    "@polkadot/api-contract": "4.2.1",
+    "@polkadot/keyring": "^6.0.5",
+    "@polkadot/types": "4.2.1",
+    "@polkadot/util": "^6.0.5",
+    "@polkadot/util-crypto": "^6.0.5",
+    "@polkadot/wasm-crypto": "^4.0.2",
+    "@types/bn.js": "^4.11.6",
+    "bn.js": "^5.1.2"
   },
   "devDependencies": {
-    "@polkadot/ts": "^0.1.56",
+    "@polkadot/ts": "^0.3.62",
     "typescript": "^3.9.7"
   }
 }

+ 11 - 22
joystream-api/scripts/export-data-directory.js

@@ -7,32 +7,21 @@
 // https://testnet.joystream.org/#/js
 
 const script = async ({ api, hashing, keyring, types, util }) => {
-  const runtimeSpecVersion = api.runtimeVersion.specVersion
 
-  const ownerAccountToMemberId = async (accountId) => {
-    const memberIds = await api.query.members.memberIdsByRootAccountId(accountId)
-    return memberIds[0] || null
-  }
+  console.log('Getting information from data directory. This may take a while')
+  const dataDirObjects = await api.query.dataDirectory.dataByContentId.entries()
 
-  const ids = await api.query.dataDirectory.knownContentIds()
-
-  // When a BTreeMap is constructed for injection the node will fail to decode
-  // it if its not sorted.
-  ids.sort()
-
-  let transformed = await Promise.all(ids.map(async (id) => {
-    let obj = await api.query.dataDirectory.dataObjectByContentId(id)
+  let transformed = await Promise.all(dataDirObjects.map(async (obj) => {
     if (obj.isNone) { return null }
-    obj = obj.unwrap()
 
-    return [id, {
-      owner: runtimeSpecVersion <= 15 ? await ownerAccountToMemberId(obj.owner) : obj.owner,
-      added_at: obj.added_at,
-      type_id: obj.type_id,
-      size: obj.size_in_bytes,
-      liaison: runtimeSpecVersion <= 15 ? new types.u64(0) : obj.liaison,
-      liaison_judgement: obj.liaison_judgement,
-      ipfs_content_id: obj.ipfs_content_id }]
+    return [obj[0], {
+      owner: obj[1].owner,
+      added_at: obj[1].added_at,
+      type_id: obj[1].type_id,
+      size: obj[1].size,
+      liaison_judgement: obj[1].liaison,
+      liaison_judgement: obj[1].liaison_judgement,
+      ipfs_content_id: obj[1].ipfs_content_id }]
   }))
 
   console.log(JSON.stringify(transformed))

+ 0 - 1
joystream-api/scripts/index.js

@@ -4,7 +4,6 @@ const exportedScripts = {}
 
 exportedScripts.example = require('./example.js')
 exportedScripts.exportDataDirectory = require('./export-data-directory.js')
-exportedScripts.injectDataObjects = require('./inject-data-objects.js')
 exportedScripts.listDataDirectory = require('./list-data-directory.js')
 
 module.exports = exportedScripts

Разница между файлами не показана из-за своего большого размера
+ 0 - 17
joystream-api/scripts/inject-data-objects.js


+ 5 - 6
joystream-api/scripts/list-data-directory.js

@@ -8,16 +8,15 @@
 // requires nicaea release+
 
 const script = async ({ api, joy }) => {
-  const ids = await api.query.dataDirectory.knownContentIds()
+  console.log('Getting information from data directory. This may take a while')
+  const dataDirObjects = await api.query.dataDirectory.dataByContentId.entries()
 
-  await Promise.all(ids.map(async (id) => {
-    let obj = await api.query.dataDirectory.dataObjectByContentId(id)
+  await Promise.all(dataDirObjects.map(async (obj) => {
     if (obj.isNone) { return }
-    obj = obj.unwrap()
-    console.log(`contentId: ${new joy.media.ContentId(id).encode()}, ipfs: ${obj.ipfs_content_id}`)
+    console.log(`contentId: ${obj[0]}, ipfs: ${obj[1].ipfs_content_id}`)
   }))
 
-  console.error(`Data Directory contains ${ids.length} objects`)
+  console.error(`Data Directory contains ${dataDirObjects.length} objects`)
 }
 
 if (typeof module === 'undefined') {

+ 13 - 84
joystream-api/src/curators/functions.ts

@@ -1,111 +1,40 @@
-import { Actor, CreateEntityOperation, EntityId, Entity, OperationType, UpdatePropertyValuesOperation } from "@joystream/types/content-directory";
+import { Actor} from "@joystream/types/content-directory";
 import { ApiPromise } from "@polkadot/api";
-import { u64, Vec } from "@polkadot/types";
+import { Vec } from "@polkadot/types";
 import { EventRecord, Extrinsic, Hash, SignedBlock } from "@polkadot/types/interfaces";
 import { AnyJson } from "@polkadot/types/types";
 
-interface NewBatch {
-  blockHeight: number,
-  action: string,
-  result: string,
-  entityIds: number[],
-  classesOfEntityIds: number[],
-  signer: string,
-  actor: AnyJson
-}
-
-interface Removed {
+interface ActionData {
   blockHeight: number,
   action: string,
   entityId: number,
-  classOfEntity: number,
   signer: string,
   actor: AnyJson
 }
 
-export async function getBatchAction(api: ApiPromise, blockHeight:number, blockHash:Hash, index:number, eventsArray: EventRecord[], result: string): Promise<NewBatch|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.sectionName
-    const extMethod = extrinsics[n].method.methodName
-    let extrinscIndex = 0
-    if (extSection == "contentDirectory" && extMethod == "transaction") {
-      extrinscIndex +=1
-      if (index == extrinscIndex) {
-        const extrinsic = extrinsics[n]
-        const actor = extrinsic.args[0] as Actor
-        const entityIds:number[] = []
-        const classesOfEntityIds:number[] = []
-        const batchOperation:NewBatch = {
-          blockHeight,
-          action: "",
-          result,
-          entityIds,
-          classesOfEntityIds,
-          signer: extrinsic.signer.toString(),
-          actor: actor.toHuman()
-        }
-        const batch = extrinsic.args[1] as Vec<OperationType>
-        for (let n=0; n<batch.length; n++) {
-          const operationType = batch[n]
-          if (operationType.value instanceof CreateEntityOperation) {
-            classesOfEntityIds.push(operationType.value.class_id.toNumber())
-            if (operationType.value.class_id.toNumber() == 10) {
-              batchOperation.action = "Video Upload"
-            } else if (operationType.value.class_id.toNumber() == 1) {
-              batchOperation.action = "Channel Creation"
-            } else {
-              batchOperation.action = "Entities created in multiple classes"
-            }
-          } else if (operationType.value instanceof UpdatePropertyValuesOperation) {
-            batchOperation.action = "Updated Entity Properties"
-          }
-        }
-        for (let i=0; i<eventsArray.length-1; i++) {
-          const entityId = eventsArray[i].event.data[1]
-          if (entityId instanceof u64) {
-            if (!batchOperation.entityIds.includes(entityId.toNumber())) {
-              batchOperation.entityIds.push(entityId.toNumber())
-            }
-          }
-        }
-        return batchOperation
-      }
-    }
-  }
-  return null
-}
-
-export async function getRemovedAction(api: ApiPromise, blockHeight:number, blockHash:Hash, removIndex: number, event: EventRecord): Promise<Removed|null> {
+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.sectionName
-    const extMethod = extrinsics[n].method.methodName
+    const extSection = extrinsics[n].method.section
+    const extMethod = extrinsics[n].method.method
     let extrinscIndex = 0
-    if (extSection == "contentDirectory" && extMethod == "removeEntity") {
+    console.log(`Extrinsics section=${extSection}, Event method=${extMethod}`)
+    if (extSection == "content" && extMethod == method) {
       extrinscIndex +=1
-      if (removIndex == extrinscIndex) {
+      if (eventIndex == extrinscIndex) {
         const extrinsic = extrinsics[n]
         const actor = extrinsic.args[0] as Actor
-        let entityId:number = -1
-        let classOfEntity:number = -1
         const ent = event.event.data[1]
-        if (ent instanceof EntityId) {
-          entityId = ent.toNumber()
-          const previousBlockHash = await api.rpc.chain.getBlockHash(blockHeight-1) as Hash
-          classOfEntity = (await api.query.contentDirectory.entityById.at(previousBlockHash,entityId) as Entity).class_id.toNumber()
-        }
-        const removedEntity:Removed = {
+        let entityId:number = +(ent.toString())
+        const video:ActionData = {
           blockHeight,
-          action: "Entity removed",
+          action: method,
           entityId,
-          classOfEntity,
           signer: extrinsic.signer.toString(),
           actor: actor.toHuman()
         }
-        return removedEntity
+        return video
       }
     }
   }

+ 21 - 17
joystream-api/src/curators/get-media-change.ts

@@ -2,7 +2,7 @@ import { WsProvider, ApiPromise } from "@polkadot/api";
 import { types } from "@joystream/types";
 import {  Vec } from "@polkadot/types";
 import { EventRecord, Hash } from "@polkadot/types/interfaces";
-import { getBatchAction, getRemovedAction } from "./functions";
+import { getChangeAction } from "./functions";
 
 
 async function main() {
@@ -19,32 +19,36 @@ async function main() {
       const blockHash = await api.rpc.chain.getBlockHash(blockHeight) as Hash
       const events = await api.query.system.events.at(blockHash) as Vec<EventRecord>;
       const eventsArray: EventRecord[] = []
-      let index = 0
-      let removIndex = 0
+      let eventIndex = 0
       for (let i=0; i<events.length; i++) {
         const section = events[i].event.section
         const method = events[i].event.method
-        if (section == "contentDirectory") {
+        if(section == 'content') {
+          console.log(`Event section=${section}, Event method=${method}`)
           eventsArray.push(events[i])
-          if (method == "EntityCreated") {
-          }
-          if (method == "EntitySchemaSupportAdded") {
+          if (method == "VideoCreated") {
+            eventIndex+=1
+            const cdChange = await getChangeAction(api, 'createVideo', blockHeight, blockHash, eventIndex, events[i])
+            console.log("Change",JSON.stringify(cdChange, null, 4))
           }
-          if (method == "EntityPropertyValuesUpdated") {
+          if (method == "VideoUpdated") {
+            eventIndex+=1
+            const cdChange = await getChangeAction(api, 'updateVideo', blockHeight, blockHash, eventIndex, events[i])
+            console.log("Change",JSON.stringify(cdChange, null, 4))
           }
-          if (method == "EntityRemoved") {
-            removIndex+=1
-            const cdChange = await getRemovedAction(api, blockHeight, blockHash, removIndex, events[i])
+          if (method == "VideoDeleted") {
+            eventIndex+=1
+            const cdChange = await getChangeAction(api, 'deleteVideo', blockHeight, blockHash, eventIndex, events[i])
             console.log("Change",JSON.stringify(cdChange, null, 4))
           }
-          if (method == "TransactionCompleted") {
-            index+=1
-            const cdChange = await getBatchAction(api, blockHeight, blockHash, index, eventsArray, method)
+          if (method == "ChannelCreated") {
+            eventIndex+=1
+            const cdChange = await getChangeAction(api, 'createChannel', blockHeight, blockHash, eventIndex, events[i])
             console.log("Change",JSON.stringify(cdChange, null, 4))
           }
-          if (method == "TransactionFailed") {
-            index+=1
-            const cdChange = await getBatchAction(api, blockHeight, blockHash, index, eventsArray, method)
+          if (method == "ChannelUpdated") {
+            eventIndex+=1
+            const cdChange = await getChangeAction(api, 'updateChannel', blockHeight, blockHash, eventIndex, events[i])
             console.log("Change",JSON.stringify(cdChange, null, 4))
           }
         }

+ 3 - 9
joystream-api/src/examples/council.ts

@@ -11,15 +11,9 @@ import { Mint, MintId } from "@joystream/types/mint";
 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://alexandria-testing-1.joystream.app/staging/rpc:9944');
-  
-  There's a bunch of tokens on the account: 5HdYzMVpJv3c4omqwKKr7SpBgzrdRRYBwoNVhJB2Y8xhUbfK,
-  with seed: "emotion soul hole loan journey what sport inject dwarf cherry ankle lesson"
-  please transfer (what you need only) to your own account, and don't test runtime upgrades :D
-  */
+
+  //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 })

+ 1 - 1
joystream-api/src/examples/functions.ts

@@ -1,7 +1,7 @@
 import { MemberId, Membership } from "@joystream/types/members";
 import { ApiPromise } from "@polkadot/api";
 import { Vec } from "@polkadot/types";
-import AccountId from "@polkadot/types/generic/AccountId";
+import { AccountId } from "@polkadot/types/interfaces";
 import { Hash } from "@polkadot/types/interfaces";
 import { Participant } from './interfaces';
 

+ 4 - 10
joystream-api/src/examples/general.ts

@@ -7,14 +7,8 @@ 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://alexandria-testing-1.joystream.app/staging/rpc:9944');
-    
-    There's a bunch of tokens on the account: 5HdYzMVpJv3c4omqwKKr7SpBgzrdRRYBwoNVhJB2Y8xhUbfK,
-    with seed: "emotion soul hole loan journey what sport inject dwarf cherry ankle lesson"
-    please transfer (what you need only) to your own account, and don't test runtime upgrades :D
-    */
+    //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 })
@@ -57,8 +51,8 @@ async function main() {
     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.sectionName
-      const method = extrinsics[i].method.methodName
+      const section = extrinsics[i].method.section
+      const method = extrinsics[i].method.method
       console.log("section",section)
       console.log("method",method)
       console.log("")

+ 6 - 12
joystream-api/src/examples/get-events-and-extrinsics.ts

@@ -7,22 +7,16 @@ 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://alexandria-testing-1.joystream.app/staging/rpc:9944');
-    
-    There's a bunch of tokens on the account: 5HdYzMVpJv3c4omqwKKr7SpBgzrdRRYBwoNVhJB2Y8xhUbfK,
-    with seed: "emotion soul hole loan journey what sport inject dwarf cherry ankle lesson"
-    please transfer (what you need only) to your own account, and don't test runtime upgrades :D
-    */
+    //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 = 1
-    const lastBlock = 10000
+    const firstBlock = 800000
+    const lastBlock = 801000
     const eventTypes:string[] = []
     const extrinsicTypes: string[] = []
     for (let blockHeight=firstBlock; blockHeight<lastBlock; blockHeight++) {
@@ -39,8 +33,8 @@ async function main() {
         }
       }
       for (let i=0; i<extrinsics.length; i++) {
-        const section = extrinsics[i].method.sectionName
-        const method = extrinsics[i].method.methodName
+        const section = extrinsics[i].method.section
+        const method = extrinsics[i].method.method
         const extrinsicType = section+`:`+method
         if (!extrinsicTypes.includes(extrinsicType)) {
           extrinsicTypes.push(extrinsicType)

+ 3 - 10
joystream-api/src/examples/proposals.ts

@@ -29,14 +29,8 @@ 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://alexandria-testing-1.joystream.app/staging/rpc:9944');
-  
-  There's a bunch of tokens on the account: 5HdYzMVpJv3c4omqwKKr7SpBgzrdRRYBwoNVhJB2Y8xhUbfK,
-  with seed: "emotion soul hole loan journey what sport inject dwarf cherry ankle lesson"
-  please transfer (what you need only) to your own account, and don't test runtime upgrades :D
-  */
+  //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 })
@@ -49,13 +43,12 @@ async function main() {
   const proposalIds = proposalKeys.map(({ args: [proposalId]}) => proposalId) as Vec<ProposalId>
   proposalIds.sort((a,b) => a.toNumber()-b.toNumber())
   console.log("number of proposals", proposalIds.length);
-  console.log("all IDs:", proposalIds.join(', '));
 
   // get all stakeIds associated with proposalIds
   const stakeIdOfProposalId = await api.query.proposalsEngine.stakesProposals.keys() as StorageKey[]
   const stakeIdsOfProposalIds = stakeIdOfProposalId.map(({ args: [stakeId]}) => stakeId) as Vec<StakeId>
   stakeIdsOfProposalIds.sort((a,b) => a.toNumber()-b.toNumber())
-  console.log("all stakeIdsOfProposalIds:", stakeIdsOfProposalIds.join(", "));
+  console.log("number of stakeIdsOfProposalIds:", stakeIdsOfProposalIds.length);
 
   for (let id of proposalIds) {
     const proposal = await api.query.proposalsEngine.proposals(id) as Proposal

+ 20 - 21
joystream-api/src/examples/working-groups.ts

@@ -2,9 +2,9 @@ import { WsProvider, ApiPromise } from "@polkadot/api";
 import { types } from "@joystream/types";
 import { Worker, WorkerId } from "@joystream/types/working-group";
 import { Null, Vec } from "@polkadot/types";
-import { Curator, CuratorApplication, CuratorApplicationId, CuratorId, CuratorInduction } from "@joystream/types/content-working-group";
 import { RewardRelationship } from "@joystream/types/recurring-rewards";
 import { Stake, StakingStatus, Staked } from "@joystream/types/stake";
+import { ApplicationOf, WorkerOf } from "@joystream/types/augment-codec/all";
 
 interface WorkingGroupStake {
   stakeId: number,
@@ -43,14 +43,8 @@ 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://alexandria-testing-1.joystream.app/staging/rpc:9944');
-  
-  There's a bunch of tokens on the account: 5HdYzMVpJv3c4omqwKKr7SpBgzrdRRYBwoNVhJB2Y8xhUbfK,
-  with seed: "emotion soul hole loan journey what sport inject dwarf cherry ankle lesson"
-  please transfer (what you need only) to your own account, and don't test runtime upgrades :D
-  */
+  //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 })
@@ -104,22 +98,27 @@ async function main() {
     }
     storageProviders.push(storageProvider)
   }
+
   // get all active content curators
-  const contentCuratorKeys = await api.query.contentWorkingGroup.curatorById.keys()
-  const contentCuratorIds = contentCuratorKeys.map(({ args: [workerId]}) => workerId) as Vec<CuratorId>
-  contentCuratorIds.sort((a,b) => a.toNumber()-b.toNumber())
-  console.log('all contentCuratorIds:', contentCuratorIds.join(', '));
-  for (let key of contentCuratorIds) {
-    const curator = await api.query.contentWorkingGroup.curatorById(key) as Curator
+  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 curatorApplicationId = (curator.induction as CuratorInduction).curator_application_id as CuratorApplicationId
-      const applicationId = await api.query.contentWorkingGroup.curatorApplicationById(curatorApplicationId) as CuratorApplication
+      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: key.toNumber(),
-        memberId: applicationId.member_id.toNumber(),
-        roleAccount: curator.role_account.toString(),
-        applicationId: applicationId.application_id.toNumber(),
+        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()

+ 2 - 1
joystream-api/src/general/script.ts

@@ -8,7 +8,7 @@ import * as joy from '@joystream/types'
 import * as hashing from '@polkadot/util-crypto'
 import { Keyring } from '@polkadot/keyring'
 
-const scripts = require('../scripts')
+const scripts = require('../../scripts')
 
 async function main () {
   
@@ -23,6 +23,7 @@ async function main () {
   }
 
   const provider = new WsProvider('ws://127.0.0.1:9944')
+  // const provider = new WsProvider('wss://testnet-rpc-2-singapore.joystream.org')
 
   const api = await ApiPromise.create({ provider, types: joyTypes })
 

Некоторые файлы не были показаны из-за большого количества измененных файлов