@polkadot/api#WsProvider TypeScript Examples

The following examples show how to use @polkadot/api#WsProvider. 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 bodhi.js with Apache License 2.0 7 votes vote down vote up
getTestProvider = (urlOverwrite?: string, opts?: ApiOptions): TestProvider => {
  const url = urlOverwrite || process.env.ENDPOINT_URL || DEFAULT_URL;

  const provider = new TestProvider({
    provider: new WsProvider(url),
    ...opts
  });

  console.log(`test provider connected to ${url}`);

  return provider;
}
Example #2
Source File: getOraclePrice.spec.ts    From guardian with Apache License 2.0 6 votes vote down vote up
describe('getOraclePrice', () => {
  it('should get the price', async (done) => {
    const ws = new WsProvider([
      'wss://testnet-node-1.laminar-chain.laminar.one/ws',
      'wss://node-6787234140909940736.jm.onfinality.io/ws'
    ]);
    const apiRx = await firstValueFrom(ApiRx.create(options({ provider: ws })));
    const oraclePrice = getOraclePrice(apiRx);
    const FEUR = apiRx.createType('CurrencyId', 'FEUR');
    oraclePrice(FEUR).subscribe((output) => {
      console.log(output);
      expect(output).toBeTruthy();
      done();
    });
  }, 60_000);
});
Example #3
Source File: tohex.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 })

    let wgId = [1, 2]

    let set = new BTreeSet<CuratorApplicationId>(api.registry, CuratorApplicationId, []);
    
    wgId.forEach((id) => {
        set.add(new CuratorApplicationId(api.registry, id))
    })
    
    /*
    Replace the integers inside the bracket in:
    let wgId:number[] = [1, 2];
    With the "WG ID"s of the curators you wish to hire, in ascending order.

    To hire "WG ID" 18 21 and 16:
    let wgId:number[] = [16, 18, 21];
    */

    console.log('copy/paste the output below to hire curator applicant(s) with WG IDs:', wgId )
    console.log(set.toHex())

    api.disconnect()
}
Example #4
Source File: providers.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
providePolkadotApi = async (port: number, isNotMoonbeam?: boolean) => {
  return isNotMoonbeam
    ? await ApiPromise.create({
        initWasm: false,
        provider: new WsProvider(`ws://localhost:${port}`),
      })
    : await ApiPromise.create({
        provider: new WsProvider(`ws://localhost:${port}`),
        typesBundle: typesBundlePre900 as any,
      });
}
Example #5
Source File: createAugmentedApi.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export function createAugmentedApi (): ApiPromise {
  const registry = new TypeRegistry();
  const metadata = new Metadata(registry, metaStatic);

  registry.setMetadata(metadata);

  const api = new ApiPromise({ provider: new WsProvider('ws://', false), registry });

  api.injectMetadata(metadata, true);

  return api;
}
Example #6
Source File: substrate.ts    From subsocial-js with GNU General Public License v3.0 6 votes vote down vote up
getSubstrateApi = async (nodeUrl?: string) => {
  if (api) return api

  const rpcEndpoint = nodeUrl || 'ws://127.0.0.1:9944/';
  const provider = new WsProvider(rpcEndpoint);

  logger.info(`Connecting to Substrate node at ${rpcEndpoint}...`);
  api = new ApiPromise({ provider, typesBundle })
  await api.isReady

  const properties = await api.rpc.system.properties() as ChainProperties
  const tokenSymbol = properties.tokenSymbol.unwrapOr(undefined)?.map((x: Text) => x.toString());
  const tokenDecimals = properties.tokenDecimals.unwrapOr(undefined)?.map((x: U32) => x.toNumber());

  registry.setChainProperties(properties)

  formatBalance.setDefaults({
    decimals: tokenDecimals,
    unit: tokenSymbol
  });

  return api
}
Example #7
Source File: GearApi.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
constructor(options: GearApiOptions = {}) {
    const { types, providerAddress, ...restOptions } = options;
    const provider = restOptions?.provider || new WsProvider(providerAddress ?? 'ws://127.0.0.1:9944');
    const defaultTypes = types ? { ...types, ...gearTypes } : gearTypes;

    super({
      provider,
      derives: {},
      types: {
        ...defaultTypes,
      },
      rpc: {
        ...gearRpc,
      },
      ...restOptions,
    });

    this.isReady.then(() => {
      this.program = new GearProgram(this);
      this.message = new GearMessage(this);
      this.balance = new GearBalance(this);
      this.reply = new GearMessageReply(this);
      this.gearEvents = new GearEvents(this);
      this.defaultTypes = defaultTypes;
      this.programState = new GearProgramState(this);
      this.blocks = new GearBlock(this);
      this.storage = new GearStorage(this);
      this.claimValueFromMailbox = new GearClaimValue(this);
      this.mailbox = new GearMailbox(this);
      this.code = new GearCode(this);
      this.waitlist = new GearWaitlist(this);
    });
  }
Example #8
Source File: AcalaGuardian.ts    From guardian with Apache License 2.0 6 votes vote down vote up
async setup(config: AcalaGuardianConfig) {
    const { network } = config;
    this._metadata = { ...this._metadata, network };

    const ws = new WsProvider(config.nodeEndpoint);
    const apiOptions = options({ provider: ws, types: customTypes });

    const apiRx = await firstValueFrom(ApiRx.create(apiOptions));

    // fetch token precision
    const properties = await firstValueFrom(apiRx.rpc.system.properties());
    const tokenSymbol = properties.tokenSymbol.unwrapOrDefault();
    const tokenDecimals = properties.tokenDecimals.unwrapOrDefault();
    if (tokenSymbol.length !== tokenDecimals.length) {
      throw Error(`Token symbols/decimals mismatch ${tokenSymbol} ${tokenDecimals}`);
    }
    tokenSymbol.forEach((symbol, index) => {
      this.tokenDecimals[symbol.toString()] = tokenDecimals[index].toNumber();
    });

    const getTokenPrecision = (token: string): number | undefined => {
      return this.tokenDecimals[token.toUpperCase()];
    };

    return { apiRx, getTokenPrecision };
  }
Example #9
Source File: ws.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
connectUpstream = async (): Promise<ApiPromise> => {
    try {
        console.debug(`[Joystream] Opening websocket ${wsLocation}`)
        const provider = new WsProvider(wsLocation)
        const api = await ApiPromise.create({ provider, types })
        await api.isReady
        console.debug(`[Joystream] Connected to ${wsLocation}`)
        return api
    } catch (e) {
        console.error(`[Joystream] upstream connection failed`, e)
        throw new Error()
    }
}
Example #10
Source File: connect.ts    From contracts-ui with GNU General Public License v3.0 6 votes vote down vote up
connect = (endpoint: string, dispatch: React.Dispatch<ApiAction>) => {
  if (!isValidWsUrl(endpoint)) return false;

  dispatch({ type: 'CONNECT_INIT' });

  const provider = new WsProvider(endpoint);
  const _api = new ApiPromise({ provider });

  // Set listeners for disconnection and reconnection event.
  _api.on('connected', async () => {
    dispatch({ type: 'CONNECT', payload: _api });
    // `ready` event is not emitted upon reconnection and is checked explicitly here.
    await _api.isReady;

    dispatch({
      type: 'CONNECT_READY',
      payload: await getChainProperties(_api),
    });
  });

  _api.on('ready', async () => {
    dispatch({
      type: 'CONNECT_READY',
      payload: await getChainProperties(_api),
    });
  });

  _api.on('error', err => dispatch({ type: 'CONNECT_ERROR', payload: err }));
}
Example #11
Source File: index.ts    From parity-bridges-ui with GNU General Public License v3.0 6 votes vote down vote up
getProviderInfo = (chainNumber: string, types: ApiOptions['types']) => {
  const providedHasher = process.env[`REACT_APP_CHAIN_${chainNumber}_CUSTOM_HASHER`];
  const providerUrl = checkEnvVariable(`REACT_APP_CHAIN_${chainNumber}_SUBSTRATE_PROVIDER`);

  const hasher = (providedHasher && hashers && hashers[providedHasher]) || null;

  const polkadotjsUrl = createPolkadotJsUrl(types!, providerUrl);
  return {
    hasher,
    provider: new WsProvider(providerUrl),
    polkadotjsUrl,
    types
  };
}
Example #12
Source File: rpc.ts    From polkadot-launch with MIT License 6 votes vote down vote up
// Connect to a local Substrate node. This function wont resolve until connected.
// TODO: Add a timeout where we know something went wrong so we don't wait forever.
export async function connect(port: number, types: any) {
	const provider = new WsProvider("ws://127.0.0.1:" + port);
	const api = await ApiPromise.create({
		provider,
		types,
		throwOnConnect: false,
	});
	return api;
}
Example #13
Source File: index.ts    From sdk with Apache License 2.0 6 votes vote down vote up
/**
 * connect to a specific node.
 *
 * @param {string} nodeEndpoint
 */
async function connect(nodes: string[]) {
  (<any>window).api = undefined;

  return new Promise(async (resolve, reject) => {
    const wsProvider = new WsProvider(nodes);
    try {
      const res = await ApiPromise.create({
        provider: wsProvider,
        metadata: {
          [`${KUSAMA_GENESIS}-9122`]: localMetadata["kusama"],
          [`${POLKADOT_GENESIS}-9122`]: localMetadata["polkadot"],
          [`${STATEMINE_GENESIS}-504`]: localMetadata["statemine"],
        } as any,
      });
      if (!(<any>window).api) {
        (<any>window).api = res;
        const url = nodes[(<any>res)._options.provider.__private_29_endpointIndex];
        send("log", `${url} wss connected success`);
        resolve(url);
      } else {
        res.disconnect();
        const url = nodes[(<any>res)._options.provider.__private_29_endpointIndex];
        send("log", `${url} wss success and disconnected`);
        resolve(url);
      }
    } catch (err) {
      send("log", `connect failed`);
      wsProvider.disconnect();
      resolve(null);
    }
  });
}
Example #14
Source File: setup.ts    From squid with GNU General Public License v3.0 6 votes vote down vote up
export function chain(): ApiPromise {
    let api = new ApiPromise({
        provider: new WsProvider(assertNotNull(process.env.CHAIN_ENDPOINT)),
        typesSpec: {
            'node-template': {
                Address: 'AccountId',
                LookupSource: 'AccountId',
                AccountInfo: 'AccountInfoWithRefCount'
            }
        }
    })
    before(() => api.isReady)
    after(() => api.disconnect())
    return api
}
Example #15
Source File: subscriber.ts    From polkadot-registrar-watcher with Apache License 2.0 6 votes vote down vote up
private _initAPI = async (): Promise<void> =>{
      const endpoints = [this.endpoint]
      const provider = new WsProvider(endpoints);
      this.api = await ApiPromise.create({provider,throwOnConnect:true,throwOnUnknown:true})
      this.api.on('disconnected', async () => { 
        await delay(120000); //2 minute timeout
        if(!this.api.isConnected) 
          this.logger.error("Impossible to reconnect... exiting...")
          process.exit(-1);
      })
      
      this.chain = await this.api.rpc.system.chain();
      const [nodeName, nodeVersion] = await Promise.all([
          this.api.rpc.system.name(),
          this.api.rpc.system.version()
      ]);
      this.logger.info(
          `You are connected to chain ${this.chain} using ${nodeName} v${nodeVersion}`
      );
    }
Example #16
Source File: subscriberTemplate.ts    From polkadot-watcher-csv-exporter with Apache License 2.0 6 votes vote down vote up
protected _initAPI = async (): Promise<void> =>{

        const endpoints = [this.endpoint] //one could define more than one endpoint
        const provider = new WsProvider(endpoints,undefined,undefined,this.apiTimeoutMs);
        this.api = await ApiPromise.create({provider,throwOnConnect:true,throwOnUnknown:true})
        this.api.on('error', (error) => {this.logger.warn("The API has an error"); console.log(error)})
        
        this.chain = await this.api.rpc.system.chain();
        const [nodeName, nodeVersion] = await Promise.all([
            this.api.rpc.system.name(),
            this.api.rpc.system.version()
        ]);
        this.logger.info(
            `You are connected to chain ${this.chain} using ${nodeName} v${nodeVersion}`
        );
    }
Example #17
Source File: chain-api.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
createApi = (endpoints: string | string[], apiOptions?: ApiOptions): ApiPromise => {
  const wsProvider = new WsProvider(endpoints);

  return new ApiPromise(
    createApiOptions({
      types: {
        ...TYPES,
        ...apiOptions?.types
      },
      provider: wsProvider,
      ...apiOptions
    })
  );
}
Example #18
Source File: get-code.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 })

  let current_block_hash = await api.rpc.chain.getBlockHash();

  console.log('getting code as of block hash', current_block_hash.toString())

  const substrateWasm = await api.query.substrate.code.at(current_block_hash.toString());
  // const substrateWasm = await api.rpc.state.getStorage('0x'+Buffer.from(':code').toString('hex'), current_block_hash);

  console.log(substrateWasm.toHex());

  api.disconnect();
}
Example #19
Source File: api.ts    From metamask-snap-polkadot with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize substrate api and awaits for it to be ready
 */
async function initApi(wsRpcUrl: string): Promise<ApiPromise> {
  provider = new WsProvider(wsRpcUrl);
  const api = await ApiPromise.create({
    initWasm: false,
    provider,
    // this seems not to make any difference anymore
    types: {
      RuntimeDbWeight: {
        read: 'Weight',
        write: 'Weight'
      }
    }
  });

  console.log("Api is ready");
  return api;
}
Example #20
Source File: epics.ts    From anthem with Apache License 2.0 6 votes vote down vote up
setBond = async (
  account: DotAccount,
  stashKey: KeyringPair,
  bond: string,
) => {
  console.log("Setting bond for account and stashKey:");
  console.log(account);
  console.log(stashKey);

  const { controllerKey } = account;
  const WS_PROVIDER_URL: string = "wss://kusama-rpc.polkadot.io/";
  const wsProvider = new WsProvider(WS_PROVIDER_URL);
  const api: ApiPromise = await ApiPromise.create({ provider: wsProvider });
  const result = await api.tx.staking
    .bond(controllerKey, bond, "Stash")
    .signAndSend(stashKey);

  console.log("Set Bond Result:");
  console.log(result);
  return result;
}
Example #21
Source File: lib.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
// if needed these could become some kind of event emitter

  /* Lifecycle */
  constructor(endpoint: string, onNodeConnectionUpdate?: (connected: boolean) => unknown) {
    const provider = new WsProvider(endpoint)
    provider.on('connected', () => {
      this.logConnectionData(endpoint)
      onNodeConnectionUpdate?.(true)
    })
    provider.on('disconnected', () => {
      onNodeConnectionUpdate?.(false)
    })
    provider.on('error', () => {
      onNodeConnectionUpdate?.(false)
    })

    this.api = new ApiPromise({ provider, types })
    const extrinsics = new JoystreamLibExtrinsics(this.api, () => this.selectedAccountId, endpoint)
    this.extrinsics = proxy(extrinsics)
  }
Example #22
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 #23
Source File: shared.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
// creates a substrate API provider and waits for it to emit a connected event
  public async createApiProvider(node: NodeInfo): Promise<WsProvider> {
    this._suppressAPIDisconnectErrors = false;
    const INTERVAL = 1000;
    const CONNECT_TIMEOUT = 10000;

    const nodeUrl = constructSubstrateUrl(node.url);
    const provider = new WsProvider(nodeUrl, INTERVAL);

    const connectedCb = () => {
      if (this.app.chain) {
        this.app.chain.networkStatus = ApiStatus.Connected;
        this.app.chain.networkError = null;
        this._suppressAPIDisconnectErrors = false;
        this._connectTime = 0;
        m.redraw();
      }
    };
    const disconnectedCb = () => {
      if (!this._suppressAPIDisconnectErrors && this.app.chain && node === this.app.chain.meta.node) {
        this.app.chain.networkStatus = ApiStatus.Disconnected;
        this.app.chain.networkError = null;
        this._suppressAPIDisconnectErrors = true;
        setTimeout(() => {
          this._suppressAPIDisconnectErrors = false;
        }, CONNECT_TIMEOUT);
        m.redraw();
      }
    };
    const errorCb = (err) => {
      console.log(`api error; waited ${this._connectTime}ms`);
      this._connectTime += INTERVAL;
      if (!this._suppressAPIDisconnectErrors && this.app.chain && node === this.app.chain.meta.node) {
        if (this.app.chain.networkStatus === ApiStatus.Connected) {
          notifyInfo('Reconnecting to chain...');
        } else {
          notifyInfo('Connecting to chain...');
        }
        this.app.chain.networkStatus = ApiStatus.Disconnected;
        this.app.chain.networkError = err.message;
        this._suppressAPIDisconnectErrors = true;
        setTimeout(() => {
          // this._suppressAPIDisconnectErrors = false;
          console.log('chain connection timed out!');
          provider.disconnect();
          this._timedOut = true;
          m.redraw();
        }, CONNECT_TIMEOUT);
        m.redraw();
      }
    };

    this._removeConnectedCb = provider.on('connected', connectedCb);
    this._removeDisconnectedCb = provider.on('disconnected', disconnectedCb);
    this._removeErrorCb = provider.on('error', errorCb);

    let unsubscribe: () => void;
    await new Promise<void>((resolve) => {
      unsubscribe = provider.on('connected', () => resolve());
    });
    if (unsubscribe) unsubscribe();
    window['wsProvider'] = provider;
    if (provider.isConnected) connectedCb();
    return provider;
  }
Example #24
Source File: index.ts    From squid with GNU General Public License v3.0 5 votes vote down vote up
export async function getApiPromise(): Promise<ApiPromise> {
  if (apiPromise) {
    return apiPromise
  }

  debug(`Creating new Api Promise`)

  const conf = getConfig()
  const provider = new WsProvider(conf.WS_PROVIDER_ENDPOINT_URI)

  const names = Object.keys(conf.TYPES_JSON)

  names.length && debug(`Injected types: ${names.join(', ')}`)

  apiPromise = await pRetry(
    async () =>
      new ApiPromise({
        provider,
        types: conf.TYPES_JSON as RegistryTypes,
        typesAlias: conf.TYPES_ALIAS as Record<string, OverrideModuleType>,
        typesBundle: conf.BUNDLE_TYPES as OverrideBundleType,
        typesSpec: conf.SPEC_TYPES as Record<string, RegistryTypes>,
        typesChain: conf.CHAIN_TYPES as Record<string, RegistryTypes>,
      }).isReadyOrError,
    {
      retries: 99, // large enough
      onFailedAttempt: (error) =>
        debug(`API failed to connect: ${JSON.stringify(error)}`),
    }
  )

  apiPromise.on('error', async (e) => {
    debug(`Api error: ${JSON.stringify(e)}, reconnecting....`)
    apiPromise = await getApiPromise()
  })

  apiPromise.on('connected', () => {
    debug(`Api connected`)
    eventEmitter.emit(IndexerEvents.API_CONNECTED)
  })

  return apiPromise
}
Example #25
Source File: useApiUrl.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
export function useApiUrl(url?: string | string[]): ApiPromise | null {
  const apiRef = useRef<ApiPromise | null>(null);
  const mountedRef = useIsMountedRef();
  const [state, setState] = useState<ApiPromise | null>(null);

  useEffect((): (() => void) => {
    return (): void => {
      disconnect(apiRef.current);
      apiRef.current = null;
    };
  }, []);

  const _setApi = useCallback(
    (api: ApiPromise | null): void => {
      disconnect(apiRef.current);

      if (mountedRef.current) {
        apiRef.current = api;
        setState(api);
      }
    },
    [mountedRef]
  );

  useEffect((): void => {
    _setApi(null);

    // eslint-disable-next-line
    url &&
      (isString(url) || url.length) &&
      ApiPromise.create({
        provider: new WsProvider(url),
        // typesBundle,
        typesChain,
      })
        .then(_setApi)
        .catch(console.error);
  }, [_setApi, url]);

  return state;
}
Example #26
Source File: providers.ts    From polkadot-launch with MIT License 5 votes vote down vote up
providePolkadotApi = async (port: number) => {
	return await ApiPromise.create({
		initWasm: false,
		provider: new WsProvider(`ws://localhost:${port}`),
	});
}
Example #27
Source File: api.ts    From metamask-snap-polkadot with Apache License 2.0 5 votes vote down vote up
provider: WsProvider
Example #28
Source File: GuardianRegistry.spec.ts    From guardian with Apache License 2.0 5 votes vote down vote up
async setup(config: BaseSubstrateGuardianConfig) {
    const ws = new WsProvider(config.nodeEndpoint);
    const apiRx = await firstValueFrom(ApiRx.create({ provider: ws }));
    return { apiRx };
  }
Example #29
Source File: testSubstrateSpec.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
testSubstrateSpec = async (specString: string, nodeUrl: string) => {
  // test out spec
  // get spec from request
  let unpackedSpec: RegisteredTypes;
  log.info('Parsing spec...');
  try {
    unpackedSpec = JSON.parse(specString);
  } catch (e) {
    throw new Error('Could not parse spec data');
  }
  const sanitizedSpec: RegisteredTypes = {
    types: unpackedSpec['types'],
    typesAlias: unpackedSpec['typesAlias'],
    typesBundle: unpackedSpec['typesBundle'],
    typesChain: unpackedSpec['typesChain'],
    typesSpec: unpackedSpec['typesSpec'],
  };

  log.info('Connecting to node...');
  const provider = new WsProvider(constructSubstrateUrl(nodeUrl), false);
  try {
    await provider.connect();
  } catch (err) {
    throw new Error('failed to connect to node url');
  }
  try {
    log.info('Fetching chain properties...');
    const api = await ApiPromise.create({ provider, ...sanitizedSpec });
    const version = api.runtimeVersion;
    const props = await api.rpc.system.properties();
    log.info(`Fetched version: ${version.specName}:${version.specVersion} and properties ${JSON.stringify(props)}`);
    log.info('Disconnecting from chain...');
    await api.disconnect();
    return sanitizedSpec;
  } catch (err) {
    log.info('Disconnecting from provider in error...');
    await provider.disconnect();
    throw new Error(`failed to initialize polkadot api: ${err.message}`);
  }
}