@polkadot/api/types#Signer TypeScript Examples

The following examples show how to use @polkadot/api/types#Signer. 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: lib.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
/* Public */
  async setActiveAccount(accountId: AccountId | null, signer?: Signer) {
    if (!accountId) {
      this._selectedAccountId = null
      this.api.setSigner({})
      return
    } else if (!signer) {
      SentryLogger.error('Missing signer for setActiveAccount', 'JoystreamLib')
      return
    }

    this._selectedAccountId = accountId
    this.api.setSigner(signer)
  }
Example #2
Source File: AccountSigner.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export default class AccountSigner implements Signer {
  readonly #keyringPair: KeyringPair;
  readonly #registry: Registry;

  constructor (registry: Registry, keyringPair: KeyringPair) {
    this.#keyringPair = keyringPair;
    this.#registry = registry;
  }

  public async signPayload (payload: SignerPayloadJSON): Promise<SignerResult> {
    return new Promise((resolve): void => {
      const signed = this.#registry.createType('ExtrinsicPayload', payload, { version: payload.version }).sign(this.#keyringPair);

      lockAccount(this.#keyringPair);
      resolve({ id: ++id, ...signed });
    });
  }
}
Example #3
Source File: ApiSigner.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export default class ApiSigner implements Signer {
  readonly #queuePayload: QueueTxPayloadAdd;
  readonly #queueSetTxStatus: QueueTxMessageSetStatus;
  readonly #registry: Registry;

  constructor (registry: Registry, queuePayload: QueueTxPayloadAdd, queueSetTxStatus: QueueTxMessageSetStatus) {
    this.#queuePayload = queuePayload;
    this.#queueSetTxStatus = queueSetTxStatus;
    this.#registry = registry;
  }

  public async signPayload (payload: SignerPayloadJSON): Promise<SignerResult> {
    return new Promise((resolve, reject): void => {
      this.#queuePayload(this.#registry, payload, (id: number, result: SignerResult | null): void => {
        if (result) {
          resolve(result);
        } else {
          reject(new Error('Unable to sign'));
        }
      });
    });
  }

  public update (id: number, result: Hash | SubmittableResult): void {
    if (result instanceof ClassOf(this.#registry, 'Hash')) {
      this.#queueSetTxStatus(id, 'sent', result.toHex());
    } else {
      this.#queueSetTxStatus(id, result.status.type.toLowerCase() as QueueTxStatus, status);
    }
  }
}
Example #4
Source File: LedgerSigner.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export default class LedgerSigner implements Signer {
  readonly #accountOffset: number;
  readonly #addressOffset: number;
  readonly #getLedger: () => Ledger;
  readonly #registry: Registry;

  constructor (registry: Registry, getLedger: () => Ledger, accountOffset: number, addressOffset: number) {
    this.#accountOffset = accountOffset;
    this.#addressOffset = addressOffset;
    this.#getLedger = getLedger;
    this.#registry = registry;
  }

  public async signPayload (payload: SignerPayloadJSON): Promise<SignerResult> {
    const raw = this.#registry.createType('ExtrinsicPayload', payload, { version: payload.version });
    const { signature } = await this.#getLedger().sign(raw.toU8a(true), this.#accountOffset, this.#addressOffset);

    return { id: ++id, signature };
  }
}
Example #5
Source File: QrSigner.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export default class QrSigner implements Signer {
  readonly #registry: Registry;
  readonly #setState: (state: QrState) => void;

  constructor (registry: Registry, setState: (state: QrState) => void) {
    this.#registry = registry;
    this.#setState = setState;
  }

  public async signPayload (payload: SignerPayloadJSON): Promise<SignerResult> {
    return new Promise((resolve, reject): void => {
      // limit size of the transaction
      const isQrHashed = (payload.method.length > 5000);
      const wrapper = this.#registry.createType('ExtrinsicPayload', payload, { version: payload.version });
      const qrPayload = isQrHashed
        ? blake2AsU8a(wrapper.toU8a(true))
        : wrapper.toU8a();

      this.#setState({
        isQrHashed,
        qrAddress: payload.address,
        qrPayload,
        qrReject: reject,
        qrResolve: resolve
      });
    });
  }
}
Example #6
Source File: polkadot_web_wallet.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
public async getSigner(who: string): Promise<Signer> {
    // finds an injector for an address
    // web wallet stores addresses in testnet format for now, so we have to re-encode
    const reencodedAddress = AddressSwapper({
      address: who,
      currentPrefix: 42,
    });
    const injector = await web3FromAddress(reencodedAddress);
    return injector.signer;
  }
Example #7
Source File: interbtc-api.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
setAccount(account: AddressOrPair, signer?: Signer): void {
        if (!(account as KeyringPair).sign && !signer) {
            throw new Error("signer must be passed if account is not a Keypair");
        }
        if (signer) {
            this.api.setSigner(signer);
        }
        this.transactionAPI.setAccount(account);
    }
Example #8
Source File: AccountSigner.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
export default class AccountSigner implements Signer {
  readonly #keyringPair: KeyringPair;
  readonly #registry: Registry;

  constructor(registry: Registry, keyringPair: KeyringPair) {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    this.#keyringPair = keyringPair;
    this.#registry = registry;
  }

  public async signPayload(payload: SignerPayloadJSON): Promise<SignerResult> {
    return new Promise((resolve): void => {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      const signed = this.#registry
        .createType('ExtrinsicPayload', payload, { version: payload.version })
        .sign(this.#keyringPair);

      lockAccount(this.#keyringPair);
      resolve({ id: ++id, ...signed });
    });
  }
}
Example #9
Source File: ApiSigner.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
export default class ApiSigner implements Signer {
  readonly #queuePayload: QueueTxPayloadAdd;
  readonly #queueSetTxStatus: QueueTxMessageSetStatus;
  readonly #registry: Registry;

  constructor(registry: Registry, queuePayload: QueueTxPayloadAdd, queueSetTxStatus: QueueTxMessageSetStatus) {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    this.#queuePayload = queuePayload;
    this.#queueSetTxStatus = queueSetTxStatus;
    this.#registry = registry;
  }

  public async signPayload(payload: SignerPayloadJSON): Promise<SignerResult> {
    return new Promise((resolve, reject): void => {
      this.#queuePayload(this.#registry, payload, (id: number, result: SignerResult | null): void => {
        if (result) {
          resolve(result);
        } else {
          reject(new Error('Unable to sign'));
        }
      });
    });
  }

  public update(id: number, result: Hash | SubmittableResult): void {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    if (result instanceof this.#registry.createClass('Hash')) {
      // if (result instanceof ClassOf(this.#registry, 'Hash')) {
      this.#queueSetTxStatus(id, 'sent', result.toHex());
    } else {
      this.#queueSetTxStatus(id, (result as SubmittableResult).status.type.toLowerCase() as QueueTxStatus, status);
    }
  }
}
Example #10
Source File: LedgerSigner.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
export default class LedgerSigner implements Signer {
  readonly accountOffset: number;
  readonly addressOffset: number;
  readonly getLedger: () => Ledger;
  readonly registry: Registry;

  constructor(registry: Registry, getLedger: () => Ledger, accountOffset: number, addressOffset: number) {
    this.accountOffset = accountOffset;
    this.addressOffset = addressOffset;
    this.getLedger = getLedger;
    this.registry = registry;
  }

  public async signPayload(payload: SignerPayloadJSON): Promise<SignerResult> {
    const raw = this.registry.createType('ExtrinsicPayload', payload, { version: payload.version });
    const { signature } = await this.getLedger().sign(raw.toU8a(true), this.accountOffset, this.addressOffset);

    return { id: ++id, signature };
  }
}
Example #11
Source File: QrSigner.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
export default class QrSigner implements Signer {
  readonly #registry: Registry;
  readonly #setState: (state: QrState) => void;

  constructor(registry: Registry, setState: (state: QrState) => void) {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    this.#registry = registry;
    this.#setState = setState;
  }

  public async signPayload(payload: SignerPayloadJSON): Promise<SignerResult> {
    return new Promise((resolve, reject): void => {
      // limit size of the transaction
      // eslint-disable-next-line no-magic-numbers
      const isQrHashed = payload.method.length > 5000;
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      const wrapper = this.#registry.createType('ExtrinsicPayload', payload, { version: payload.version });
      const qrPayload = isQrHashed ? blake2AsU8a(wrapper.toU8a(true)) : wrapper.toU8a();

      this.#setState({
        isQrHashed,
        qrAddress: payload.address,
        qrPayload,
        qrReject: reject,
        qrResolve: resolve,
      });
    });
  }
}
Example #12
Source File: SingleAccountSigner.ts    From interbtc-api with Apache License 2.0 5 votes vote down vote up
export class SingleAccountSigner implements Signer {
  readonly #keyringPair: KeyringPair;

  readonly #registry: Registry;

  readonly #signDelay: number;

  constructor (registry: Registry, keyringPair: KeyringPair, signDelay = 0) {
      this.#keyringPair = keyringPair;
      this.#registry = registry;
      this.#signDelay = signDelay;
  }

  public async signPayload (payload: SignerPayloadJSON): Promise<SignerResult> {
      if (payload.address !== this.#keyringPair.address) {
          throw new Error("does not have the keyringPair");
      }

      return new Promise((resolve): void => {
          setTimeout((): void => {
              const signed = this.#registry.createType("ExtrinsicPayload", payload, { version: payload.version }).sign(this.#keyringPair);

              resolve({
                  id: ++id,
                  ...signed
              });
          }, this.#signDelay);
      });
  }

  public async signRaw ({ address, data }: SignerPayloadRaw): Promise<SignerResult> {
      if (address !== this.#keyringPair.address) {
          throw new Error("does not have the keyringPair");
      }

      return new Promise((resolve): void => {
          setTimeout((): void => {
              const signature = u8aToHex(this.#keyringPair.sign(hexToU8a(data)));

              resolve({
                  id: ++id,
                  signature
              });
          }, this.#signDelay);
      });
  }
}
Example #13
Source File: shared.ts    From commonwealth with GNU General Public License v3.0 4 votes vote down vote up
public createTXModalData(
    author: SubstrateAccount,
    txFunc: (api: ApiPromise) => SubmittableExtrinsic<'promise'>,
    txName: string,
    objName: string,
    cb?: (success: boolean) => void, // TODO: remove this argument
  ): ITXModalData {
    // TODO: check if author has funds for tx fee
    const events = new EventEmitter();
    return {
      author,
      txType: txName,
      cb,
      txData: {
        events,
        unsignedData: async (): Promise<ISubstrateTXData> => {
          const txHex = txFunc(this.api).method.toHex();
          const nonce = this.api.query.system.accountNonce
            ? await this.api.query.system.accountNonce(author.address)
            : (await this.api.query.system.account(author.address)).nonce;
          const genesisHash = this.api.genesisHash.toHex();
          return {
            call: txHex,
            nonce: (+nonce).toString(),
            blockHash: genesisHash,
            isEd25519: author.isEd25519,
          };
        },
        transact: (hexTxOrAddress?: string, signer?: Signer): void => {
          let unsubscribe: Promise<VoidFn>;
          const txResultHandler = (result: SubmittableResult) => {
            const status = result.status;
            if (status.isReady) {
              console.log(`Pending ${txName}: "${objName}"`);
              events.emit(TransactionStatus.Ready.toString(), {});
            } else if (status.isFinalized || status.isInBlock) {
              for (const e of result.events) {
                if (this.api.events.system.ExtrinsicSuccess.is(e.event)) {
                  notifySuccess(`Confirmed ${txName}`);
                  events.emit(TransactionStatus.Success.toString(), {
                    hash: status.isFinalized ? status.asFinalized.toHex() : status.asInBlock.toHex(),
                    blocknum: this.app.chain.block.height,
                    timestamp: this.app.chain.block.lastTime,
                  });
                  if (unsubscribe) unsubscribe.then((u) => u());
                } else if (this.api.events.system.ExtrinsicFailed.is(e.event)) {
                  const errorData = e.event.data[0] as unknown as DispatchError;
                  let errorInfo;
                  if (errorData.isModule) {
                    const decoded = this.registry.findMetaError(errorData.asModule);
                    const { docs, method, section } = decoded;
                    errorInfo = `${section}.${method}: ${docs.join(' ')}`;
                  } else if (errorData.isBadOrigin) {
                    errorInfo = 'TX Error: invalid sender origin';
                  } else if (errorData.isCannotLookup) {
                    errorInfo = 'TX Error: cannot lookup call';
                  } else {
                    errorInfo = 'TX Error: unknown';
                  }
                  console.error(errorInfo);
                  notifyError(`Failed ${txName}: "${objName}"`);
                  events.emit(TransactionStatus.Failed.toString(), {
                    hash: status.isFinalized ? status.asFinalized.toHex() : status.asInBlock.toHex(),
                    blocknum: this.app.chain.block.height,
                    timestamp: this.app.chain.block.lastTime,
                    err: errorInfo,
                  });
                  if (unsubscribe) unsubscribe.then((u) => u());
                }
              }
            }
          };
          try {
            if (signer) {
              this.api.setSigner(signer);
              unsubscribe = txFunc(this.api).signAndSend(hexTxOrAddress, txResultHandler);
            } else if (hexTxOrAddress) {
              unsubscribe = this.api.tx(hexTxOrAddress).send(txResultHandler);
            } else {
              throw new Error('no signer found');
            }
          } catch (err) {
            if (err.message.indexOf('1014: Priority is too low') !== -1) {
              notifyError('Another transaction is already queued for processing');
            } else {
              notifyError(err.toString());
            }
            m.redraw();
            events.emit(TransactionStatus.Error.toString(), { err: err.toString() });
          }
        },
      }
    };
  }