@polkadot/types#Bytes TypeScript Examples

The following examples show how to use @polkadot/types#Bytes. 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: Code.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Submit code without initialization
   * @param code
   * @returns Code hash
   */
  submit(code: Buffer | Uint8Array): { codeHash: Hex; submitted: SubmittableExtrinsic<'promise', ISubmittableResult> } {
    const codeBytes = this.createType.create('bytes', Array.from(code)) as Bytes;
    this.submitted = this.api.tx.gear.submitCode(codeBytes);
    const codeHash = generateCodeHash(code);
    return { codeHash, submitted: this.submitted };
  }
Example #2
Source File: OpaqueCall.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function OpaqueCall(props: Props): React.ReactElement<Props> {
  if (!props.isDisabled) {
    return <Unknown {...props} />;
  }

  const value = props.registry.createType('Call', (props.defaultValue.value as Bytes).toHex());

  return <CallDisplay {...props} defaultValue={{ isValid: true, value }} />;
}
Example #3
Source File: gov.ts    From sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Query tips of treasury.
 */
async function getTreasuryTips(api: ApiPromise) {
  const tipKeys = await (api.query.tips || api.query.treasury).tips.keys();
  const tipHashes = tipKeys.map((key) => key.args[0].toHex());
  const optTips = (await (api.query.tips || api.query.treasury).tips.multi(tipHashes)) as Option<OpenTip>[];
  const tips = optTips
    .map((opt, index) => [tipHashes[index], opt.unwrapOr(null)])
    .filter((val) => !!val[1])
    .sort((a: any[], b: any[]) => a[1].closes.unwrapOr(BN_ZERO).cmp(b[1].closes.unwrapOr(BN_ZERO)));
  return Promise.all(
    tips.map(async (tip: any[]) => {
      const detail = tip[1].toJSON();
      const reason = (await (api.query.tips || api.query.treasury).reasons(detail.reason)) as Option<Bytes>;
      const tips = detail.tips.map((e: any) => ({
        address: e[0],
        value: e[1],
      }));
      return {
        hash: tip[0],
        ...detail,
        reason: reason.isSome ? hexToString(reason.unwrap().toHex()) : null,
        tips,
      };
    })
  );
}
Example #4
Source File: bitcoin.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
export async function getTxProof(
    electrsAPI: ElectrsAPI,
    btcTxId: string
): Promise<{ merkleProof: Bytes; rawTx: Bytes }> {
    const [merkleProof, rawTx] = await electrsAPI.getParsedExecutionParameters(btcTxId);
    return {
        merkleProof,
        rawTx,
    };
}
Example #5
Source File: electrs.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
async getParsedExecutionParameters(txid: string): Promise<[Bytes, Bytes]> {
        const [unparsedMerkleProof, unparsedRawTx] = await Promise.all([
            this.getMerkleProof(txid),
            this.getRawTransaction(txid),
        ]);
        // To avoid taking an ApiPromise object as a constructor parameter,
        // use the default TypeRegistry (without custom type metadata),
        // because the Bytes type instantiated is provided by default.
        const registry = new TypeRegistry();

        const merkleProof = registry.createType("Bytes", "0x" + unparsedMerkleProof);
        const rawTx = registry.createType("Bytes", "0x" + unparsedRawTx);
        return [merkleProof, rawTx];
    }
Example #6
Source File: CreateType.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
private createType(type: string, data: any): Codec {
    if (typeIsString(type)) {
      return this.registry.createType('String', data);
    } else if (type.toLowerCase() === 'bytes') {
      if (data instanceof Uint8Array) {
        return this.registry.createType('Bytes', Array.from(data));
      } else if (data instanceof Bytes) {
        return data;
      }
      return this.registry.createType('Bytes', data);
    } else {
      return this.registry.createType(type, data);
    }
  }
Example #7
Source File: helpers.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
prepareAssetsForExtrinsic = async (api: PolkadotApi, dataObjectsMetadata: DataObjectMetadata[]) => {
  if (!dataObjectsMetadata.length) {
    return null
  }

  const feePerMB = await api.query.storage.dataObjectPerMegabyteFee()
  const feePerMBUint = new u128(api.registry, feePerMB)

  const mappedDataObjectMetadata = dataObjectsMetadata.map((metadata) => ({
    size: metadata.size,
    ipfsContentId: new Bytes(api.registry, metadata.ipfsHash),
  }))
  const dataObjectsVec = new Vec(api.registry, DataObjectCreationParameters, mappedDataObjectMetadata)

  return new StorageAssets(api.registry, {
    expected_data_size_fee: feePerMBUint,
    object_creation_list: dataObjectsVec,
  })
}
Example #8
Source File: OpaqueCall.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function OpaqueCall (props: Props): React.ReactElement<Props> {
  if (!props.isDisabled) {
    return (
      <Unknown {...props} />
    );
  }

  const value = props.registry.createType('Call', (props.defaultValue.value as Bytes).toHex());

  return (
    <CallDisplay
      {...props}
      defaultValue={{ isValid: true, value }}
    />
  );
}
Example #9
Source File: tobytes.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
async function main() {
  const provider = new WsProvider('ws://127.0.0.1:9944');
  const api = await ApiPromise.create({ provider, types })

  const input:string = "myInputString"
  const output = new Bytes(api.registry, input);

  /*
  Some extrinsics require input as "Bytes".
  Replace <myInputString> with the string you want, and the output can be pasted in.
  */


  console.log("input string", input)
  console.log("output, as bytes toHex",output.toHex())
  api.disconnect()
}
Example #10
Source File: metadata.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
parseMemberExtrinsicInput: ParseExtrinsicInputFn<MemberInputMetadata, undefined> = async (
  api,
  inputMetadata
) => {
  const memberProperties: IMembershipMetadata = {}
  if (inputMetadata.name != null) {
    memberProperties.name = inputMetadata.name
  }
  if (inputMetadata.about != null) {
    memberProperties.about = inputMetadata.about
  }
  if (inputMetadata.avatarUri != null) {
    memberProperties.avatarUri = inputMetadata.avatarUri
  }

  const serializedMemberMetadata = MembershipMetadata.encode(memberProperties).finish()
  const memberMetadataRaw = new Raw(api.registry, serializedMemberMetadata)
  const memberMetadataBytes = new Bytes(api.registry, memberMetadataRaw)
  const optionalMemberMetadataBytes = new Option(api.registry, Bytes, memberMetadataBytes)

  return [optionalMemberMetadataBytes, undefined]
}
Example #11
Source File: helpers.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
createNftIssuanceParameters = (
  registry: Registry,
  inputMetadata?: NftIssuanceInputMetadata
): NftIssuanceParameters | null => {
  if (!inputMetadata) {
    return null
  }

  const initTransactionalStatus = createNftIssuanceTransactionalStatus(registry, inputMetadata)

  return new NftIssuanceParameters(registry, {
    nft_metadata: new Bytes(registry, '0x0'),
    royalty: new Option(
      registry,
      Royalty,
      inputMetadata.royalty ? inputMetadata.royalty * NFT_PERBILL_PERCENT : undefined
    ),
    init_transactional_status: initTransactionalStatus,
    non_channel_owner: new Option(registry, RuntimeMemberId),
  })
}
Example #12
Source File: Queue.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function extractEvents (result?: SubmittableResult): ActionStatus[] {
  return mergeStatus(
    ((result && result.events) || [])
      // filter events handled globally, or those we are not interested in, these are
      // handled by the global overview, so don't add them here
      .filter((record): boolean => !!record.event && record.event.section !== 'democracy')
      .map(({ event: { data, method, section } }): ActionStatusPartial => {
        if (section === 'system' && method === 'ExtrinsicFailed') {
          const [dispatchError] = data as unknown as ITuple<[DispatchError]>;
          let message = dispatchError.type;

          if (dispatchError.isModule) {
            try {
              const mod = dispatchError.asModule;
              const error = dispatchError.registry.findMetaError(mod);

              message = `${error.section}.${error.name}`;
            } catch (error) {
              // swallow
            }
          }

          return {
            action: `${section}.${method}`,
            message,
            status: 'error'
          };
        } else if (section === 'contracts') {
          if (method === 'ContractExecution' && data.length === 2) {
            // see if we have info for this contract
            const [accountId, encoded] = data;

            try {
              const abi = getContractAbi(accountId.toString());

              if (abi) {
                const decoded = abi.decodeEvent(encoded as Bytes);

                return {
                  action: decoded.event.identifier,
                  message: 'contract event',
                  status: 'event'
                };
              }
            } catch (error) {
              // ABI mismatch?
              console.error(error);
            }
          } else if (method === 'Evicted') {
            return {
              action: `${section}.${method}`,
              message: 'contract evicted',
              status: 'error'
            };
          }
        }

        return {
          action: `${section}.${method}`,
          message: EVENT_MESSAGE,
          status: 'event'
        };
      })
  );
}
Example #13
Source File: Event.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function EventDisplay ({ children, className = '', value }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const params = value.typeDef.map(({ type }) => ({ type: getTypeDef(type) }));
  const values = value.data.map((value) => ({ isValid: true, value }));

  const abiEvent = useMemo(
    (): AbiEvent | null => {
      // for contracts, we decode the actual event
      if (value.section === 'contracts' && value.method === 'ContractExecution' && value.data.length === 2) {
        // see if we have info for this contract
        const [accountId, encoded] = value.data;

        try {
          const abi = getContractAbi(accountId.toString());

          if (abi) {
            const decoded = abi.decodeEvent(encoded as Bytes);

            return {
              ...decoded,
              values: decoded.args.map((value) => ({ isValid: true, value }))
            };
          }
        } catch (error) {
          // ABI mismatch?
          console.error(error);
        }
      }

      return null;
    },
    [value]
  );

  return (
    <div className={`ui--Event ${className}`}>
      {children}
      <Params
        isDisabled
        params={params}
        values={values}
      >
        {abiEvent && (
          <>
            <Input
              isDisabled
              label={t<string>('contract event')}
              value={abiEvent.event.identifier}
            />
            <Params
              isDisabled
              params={abiEvent.event.args}
              values={abiEvent.values}
            />
          </>
        )}
      </Params>
    </div>
  );
}
Example #14
Source File: TipReason.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
transformTip = {
  transform: (optBytes: Option<Bytes>) =>
    optBytes.isSome
      ? hexToString(optBytes.unwrap().toHex())
      : null
}
Example #15
Source File: Program.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
/**
   * @param program Upload program data
   * @param meta Metadata
   * @returns ProgramId
   * @example
   * ```javascript
   * const code = fs.readFileSync('path/to/program.opt.wasm');
   * const meta = await getWasmMetadata(fs.readFileSync('path/to/program.meta.wasm'));
   * const api = await GearApi.create();
   * const { programId, salt, submitted } = api.program.submit({
   *   code,
   *   initPayload: {field: 'someValue'},
   *   gasLimit: 20_000_000,
   * }, meta)
   * api.program.signAndSend(account, (events) => {
   *   events.forEach(({event}) => console.log(event.toHuman()))
   * })
   * ```
   */
  submit(
    program: {
      code: Buffer | Uint8Array;
      salt?: `0x${string}`;
      initPayload?: string | any;
      gasLimit: u64 | AnyNumber;
      value?: BalanceOf | AnyNumber;
    },
    meta?: Metadata,
    messageType?: string,
  ): { programId: Hex; salt: Hex; submitted: SubmittableExtrinsic<'promise', ISubmittableResult> } {
    const salt = program.salt || randomAsHex(20);
    const code = this.createType.create('bytes', Array.from(program.code)) as Bytes;
    let payload = createPayload(this.createType, messageType || meta?.init_input, program.initPayload, meta);
    try {
      this.submitted = this.api.tx.gear.submitProgram(code, salt, payload, program.gasLimit, program.value || 0);
      const programId = generateProgramId(code, salt);
      return { programId, salt, submitted: this.submitted };
    } catch (error) {
      throw new SubmitProgramError();
    }
  }
Example #16
Source File: metadata.ts    From atlas with GNU General Public License v3.0 5 votes vote down vote up
parseChannelExtrinsicInput: ParseExtrinsicInputFn<ChannelInputMetadata, ChannelInputAssets> = async (
  api,
  inputMetadata,
  inputAssets
) => {
  const channelProperties: IChannelMetadata = {}

  // prepare data objects and assign proper indexes in metadata
  const channelDataObjectsMetadata: DataObjectMetadata[] = [
    ...(inputAssets.avatarPhoto ? [inputAssets.avatarPhoto] : []),
    ...(inputAssets.coverPhoto ? [inputAssets.coverPhoto] : []),
  ]
  const channelStorageAssets = await prepareAssetsForExtrinsic(api, channelDataObjectsMetadata)
  if (inputAssets.avatarPhoto) {
    channelProperties.avatarPhoto = 0
  }
  if (inputAssets.coverPhoto) {
    channelProperties.coverPhoto = inputAssets.avatarPhoto ? 1 : 0
  }

  if (inputMetadata.title != null) {
    channelProperties.title = inputMetadata.title
  }
  if (inputMetadata.description != null) {
    channelProperties.description = inputMetadata.description
  }
  if (inputMetadata.isPublic != null) {
    channelProperties.isPublic = inputMetadata.isPublic
  }
  if (inputMetadata.language != null) {
    channelProperties.language = inputMetadata.language
  }

  const serializedChannelMetadata = ChannelMetadata.encode(channelProperties).finish()
  const channelMetadataRaw = new Raw(api.registry, serializedChannelMetadata)
  const channelMetadataBytes = new Bytes(api.registry, channelMetadataRaw)
  const optionalChannelMetadataBytes = new Option(api.registry, Bytes, channelMetadataBytes)

  const optionalChannelStorageAssets = new Option(api.registry, StorageAssets, channelStorageAssets)

  return [optionalChannelMetadataBytes, optionalChannelStorageAssets]
}
Example #17
Source File: Event.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function EventDisplay({ children, className = '', value }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const params = value.typeDef.map(({ type }) => ({ type: getTypeDef(type) }));
  const values = value.data.map((value) => ({ isValid: true, value }));

  // eslint-disable-next-line complexity
  const abiEvent = useMemo((): AbiEvent | null => {
    // for contracts, we decode the actual event
    // eslint-disable-next-line no-magic-numbers
    if (value.section === 'contracts' && value.method === 'ContractExecution' && value.data.length === 2) {
      // see if we have info for this contract
      const [accountId, encoded] = value.data;

      try {
        const abi = getContractAbi(accountId.toString());

        if (abi) {
          const decoded = abi.decodeEvent(encoded as Bytes);

          return {
            ...decoded,
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            values: decoded.args.map((value: any) => ({ isValid: true, value })),
          };
        }
      } catch (error) {
        // ABI mismatch?
        console.error(error);
      }
    }

    return null;
  }, [value]);

  return (
    <div className={`ui--Event ${className}`}>
      {children}
      <Params isDisabled params={params} values={values}>
        {abiEvent && (
          <>
            <Input isDisabled label={t<string>('contract event')} value={abiEvent.event.identifier} />
            <Params isDisabled params={abiEvent.event.args} values={abiEvent.values} />
          </>
        )}
      </Params>
    </div>
  );
}
Example #18
Source File: Queue.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function extractEvents(result?: SubmittableResult): ActionStatus[] {
  return mergeStatus(
    ((result && result.events) || [])
      // filter events handled globally, or those we are not interested in, these are
      // handled by the global overview, so don't add them here
      .filter((record): boolean => !!record.event && record.event.section !== 'democracy')
      // eslint-disable-next-line complexity
      .map(({ event: { data, method, section } }): ActionStatusPartial => {
        if (section === 'system' && method === 'ExtrinsicFailed') {
          const [dispatchError] = data as unknown as ITuple<[DispatchError]>;
          let message: string = dispatchError.type;

          if (dispatchError.isModule) {
            try {
              const mod = dispatchError.asModule;
              const error = dispatchError.registry.findMetaError(mod);

              message = `${error.section}.${error.name}`;
            } catch (error) {
              // swallow
            }
          } else if (dispatchError.isToken) {
            message = `${dispatchError.type}.${dispatchError.asToken.type}`;
          }

          return {
            action: `${section}.${method}`,
            message,
            status: 'error',
          };
        } else if (section === 'contracts') {
          // eslint-disable-next-line no-magic-numbers
          if (method === 'ContractExecution' && data.length === 2) {
            // see if we have info for this contract
            const [accountId, encoded] = data;

            try {
              const abi = getContractAbi(accountId.toString());

              if (abi) {
                const decoded = abi.decodeEvent(encoded as Bytes);

                return {
                  action: decoded.event.identifier,
                  message: 'contract event',
                  status: 'event',
                };
              }
            } catch (error) {
              // ABI mismatch?
              console.error(error);
            }
          } else if (method === 'Evicted') {
            return {
              action: `${section}.${method}`,
              message: 'contract evicted',
              status: 'error',
            };
          }
        }

        return {
          action: `${section}.${method}`,
          message: EVENT_MESSAGE,
          status: 'event',
        };
      })
  );
}
Example #19
Source File: useApiCalls.ts    From parity-bridges-ui with GNU General Public License v3.0 4 votes vote down vote up
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 #20
Source File: metadata.ts    From atlas with GNU General Public License v3.0 4 votes vote down vote up
parseVideoExtrinsicInput: ParseExtrinsicInputFn<VideoInputMetadata, VideoInputAssets> = async (
  api,
  inputMetadata,
  inputAssets
) => {
  const videoProperties: IVideoMetadata = {}

  // prepare data objects and assign proper indexes in metadata
  const videoDataObjectsMetadata: DataObjectMetadata[] = [
    ...(inputAssets.media ? [inputAssets.media] : []),
    ...(inputAssets.thumbnailPhoto ? [inputAssets.thumbnailPhoto] : []),
  ]
  const videoStorageAssets = await prepareAssetsForExtrinsic(api, videoDataObjectsMetadata)
  if (inputAssets.media) {
    videoProperties.video = 0
  }
  if (inputAssets.thumbnailPhoto) {
    videoProperties.thumbnailPhoto = inputAssets.media ? 1 : 0
  }

  if (inputMetadata.title != null) {
    videoProperties.title = inputMetadata.title
  }
  if (inputMetadata.description != null) {
    videoProperties.description = inputMetadata.description
  }
  if (inputMetadata.isPublic != null) {
    videoProperties.isPublic = inputMetadata.isPublic
  }
  if (inputMetadata.language != null) {
    videoProperties.language = inputMetadata.language
  }
  if (inputMetadata.isExplicit != null) {
    videoProperties.isExplicit = inputMetadata.isExplicit
  }
  if (inputMetadata.category != null) {
    videoProperties.category = Long.fromInt(inputMetadata.category)
  }
  if (inputMetadata.duration != null) {
    videoProperties.duration = inputMetadata.duration
  }
  if (inputMetadata.mediaPixelHeight != null) {
    videoProperties.mediaPixelHeight = inputMetadata.mediaPixelHeight
  }
  if (inputMetadata.mediaPixelWidth != null) {
    videoProperties.mediaPixelWidth = inputMetadata.mediaPixelWidth
  }
  if (inputMetadata.hasMarketing != null) {
    videoProperties.hasMarketing = inputMetadata.hasMarketing
  }

  if (inputMetadata.license) {
    const videoLicenseProperties: ILicense = {}
    if (inputMetadata.license.code != null) {
      videoLicenseProperties.code = inputMetadata.license.code
    }
    if (inputMetadata.license.attribution != null) {
      videoLicenseProperties.attribution = inputMetadata.license.attribution
    }
    if (inputMetadata.license.customText != null) {
      videoLicenseProperties.customText = inputMetadata.license.customText
    }

    videoProperties.license = videoLicenseProperties
  }

  if (inputMetadata.mimeMediaType != null) {
    const videoMediaTypeProperties: IMediaType = {}
    videoMediaTypeProperties.mimeMediaType = inputMetadata.mimeMediaType
    videoProperties.mediaType = videoMediaTypeProperties
  }

  if (inputMetadata.publishedBeforeJoystream != null) {
    const videoPublishedBeforeProperties: IPublishedBeforeJoystream = {}
    videoPublishedBeforeProperties.isPublished = true
    videoPublishedBeforeProperties.date = inputMetadata.publishedBeforeJoystream
    videoProperties.publishedBeforeJoystream = videoPublishedBeforeProperties
  }

  const serializedVideoMetadata = VideoMetadata.encode(videoProperties).finish()
  const videoMetadataRaw = new Raw(api.registry, serializedVideoMetadata)
  const videoMetadataBytes = new Bytes(api.registry, videoMetadataRaw)
  const optionalVideoMetadataBytes = new Option(api.registry, Bytes, videoMetadataBytes)

  const optionalVideoStorageAssets = new Option(api.registry, StorageAssets, videoStorageAssets)

  return [optionalVideoMetadataBytes, optionalVideoStorageAssets]
}